Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9cb96eaf76 | |||
| c5207759a8 | |||
| b14cd502ce | |||
| 3a3bb843e5 | |||
| a2f961aebb | |||
| bd508cdcee | |||
| 46051fd248 | |||
| eed4df564d | |||
| 6ac6a1fd2d | |||
| adf3f2ddbc | |||
| 2daebbfa23 | |||
| 9a23db7e43 | |||
| 3be87f19dd | |||
| b7d4286c44 |
@@ -7,8 +7,4 @@ python:
|
||||
- "pypy"
|
||||
- "pypy3"
|
||||
|
||||
install:
|
||||
- "pip install -r requirements.dev.txt"
|
||||
- "pip install ."
|
||||
|
||||
script: python setup.py test
|
||||
|
||||
+10
@@ -2,6 +2,16 @@
|
||||
Changelog
|
||||
=========
|
||||
|
||||
0.3.1
|
||||
=====
|
||||
|
||||
* Fix how empty responses are handled
|
||||
|
||||
0.3.0
|
||||
=====
|
||||
|
||||
* Added method to unsuspend suspended user
|
||||
|
||||
0.2.0
|
||||
=====
|
||||
|
||||
|
||||
+5
-1
@@ -2,6 +2,10 @@
|
||||
pydiscourse
|
||||
===========
|
||||
|
||||
.. image:: https://secure.travis-ci.org/bennylope/pydiscourse.svg?branch=master
|
||||
:alt: Build Status
|
||||
:target: http://travis-ci.org/bennylope/pydiscourse
|
||||
|
||||
A Python library for working with Discourse.
|
||||
|
||||
This is a fork of the original Tindie version. It was forked to include fixes,
|
||||
@@ -20,7 +24,7 @@ Examples
|
||||
|
||||
Create a client connection to a Discourse server::
|
||||
|
||||
from pydiscourse.client import DiscourseClient
|
||||
from pydiscourse import DiscourseClient
|
||||
client = DiscourseClient(
|
||||
'http://example.com',
|
||||
api_username='username',
|
||||
|
||||
+2
-2
@@ -53,9 +53,9 @@ copyright = u'2014, Marc Sibson'
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '0.2.0'
|
||||
version = '0.3'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '0.2.0'
|
||||
release = '0.3.1'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
__version__ = '0.2.0'
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
__version__ = '0.3.1'
|
||||
|
||||
from pydiscourse.client import DiscourseClient
|
||||
|
||||
Executable → Regular
+460
-24
@@ -1,9 +1,13 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
Core API client module
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
import requests
|
||||
|
||||
from pydiscourse.exceptions import DiscourseError, DiscourseServerError, DiscourseClientError
|
||||
from pydiscourse.exceptions import (
|
||||
DiscourseError, DiscourseServerError, DiscourseClientError)
|
||||
from pydiscourse.sso import sso_payload
|
||||
|
||||
|
||||
@@ -11,53 +15,185 @@ log = logging.getLogger('pydiscourse.client')
|
||||
|
||||
|
||||
class DiscourseClient(object):
|
||||
""" A basic client for the Discourse API that implements the raw API
|
||||
"""Discourse API client"""
|
||||
|
||||
This class will attempt to remain roughly similar to the discourse_api rails API
|
||||
"""
|
||||
def __init__(self, host, api_username, api_key, timeout=None):
|
||||
"""
|
||||
Initialize the client
|
||||
|
||||
Args:
|
||||
host: full domain name including scheme for the Discourse API
|
||||
api_username: username to connect with
|
||||
api_key: API key to connect with
|
||||
timeout: optional timeout for the request (in seconds)
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
self.host = host
|
||||
self.api_username = api_username
|
||||
self.api_key = api_key
|
||||
self.timeout = timeout
|
||||
|
||||
def user(self, username):
|
||||
"""
|
||||
Get user information for a specific user
|
||||
|
||||
TODO: include sample data returned
|
||||
TODO: what happens when no user is found?
|
||||
|
||||
Args:
|
||||
username: username to return
|
||||
|
||||
Returns:
|
||||
dict of user information
|
||||
|
||||
"""
|
||||
return self._get('/users/{0}.json'.format(username))['user']
|
||||
|
||||
def create_user(self, name, username, email, password, **kwargs):
|
||||
""" active='true', to avoid sending activation emails
|
||||
"""
|
||||
Create a Discourse user
|
||||
|
||||
Set keyword argument active='true' to avoid sending activation emails
|
||||
|
||||
TODO: allow optional password and generate a random one
|
||||
|
||||
Args:
|
||||
name: the full name of the new user
|
||||
username: their username (this is a key... that they can change)
|
||||
email: their email, will be used for activation and summary emails
|
||||
password: their initial password
|
||||
**kwargs: ???? what else can be sent through?
|
||||
|
||||
Returns:
|
||||
????
|
||||
|
||||
"""
|
||||
r = self._get('/users/hp.json')
|
||||
challenge = r['challenge'][::-1] # reverse challenge, discourse security check
|
||||
confirmations = r['value']
|
||||
return self._post('/users', name=name, username=username, email=email,
|
||||
password=password, password_confirmation=confirmations, challenge=challenge, **kwargs)
|
||||
password=password, password_confirmation=confirmations,
|
||||
challenge=challenge, **kwargs)
|
||||
|
||||
def by_external_id(self, external_id):
|
||||
def user_by_external_id(self, external_id):
|
||||
"""
|
||||
|
||||
Args:
|
||||
external_id:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
response = self._get("/users/by-external/{0}".format(external_id))
|
||||
return response['user']
|
||||
by_external_id = user_by_external_id
|
||||
|
||||
def log_out(self, userid):
|
||||
"""
|
||||
|
||||
Args:
|
||||
userid:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._post('/admin/users/{0}/log_out'.format(userid))
|
||||
|
||||
def trust_level(self, userid, level):
|
||||
"""
|
||||
|
||||
Args:
|
||||
userid:
|
||||
level:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
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)
|
||||
"""
|
||||
Suspend a user's account
|
||||
|
||||
Args:
|
||||
userid: the Discourse user ID
|
||||
duration: the length of time in days for which a user's account
|
||||
should be suspended
|
||||
reason: the reason for suspending the account
|
||||
|
||||
Returns:
|
||||
????
|
||||
|
||||
"""
|
||||
return self._put('/admin/users/{0}/suspend'.format(userid),
|
||||
duration=duration, reason=reason)
|
||||
|
||||
def unsuspend(self, userid):
|
||||
"""
|
||||
Unsuspends a user's account
|
||||
|
||||
Args:
|
||||
userid: the Discourse user ID
|
||||
|
||||
Returns:
|
||||
None???
|
||||
"""
|
||||
return self._put('/admin/users/{0}/unsuspend'.format(userid))
|
||||
|
||||
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)
|
||||
"""
|
||||
|
||||
optional user search: filter='test@example.com' or filter='scott'
|
||||
|
||||
Args:
|
||||
type:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get('/admin/users/list/{0}.json'.format(type), **kwargs)
|
||||
|
||||
def update_avatar_from_url(self, username, url, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
url:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._post('/users/{0}/preferences/avatar'.format(username), file=url, **kwargs)
|
||||
|
||||
def update_avatar_image(self, username, img, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
img:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
files = {'file': img}
|
||||
return self._post('/users/{0}/preferences/avatar'.format(username), files=files, **kwargs)
|
||||
|
||||
def toggle_gravatar(self, username, state=True, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
state:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
url = '/users/{0}/preferences/avatar/toggle'.format(username)
|
||||
if bool(state):
|
||||
kwargs['use_uploaded_avatar'] = 'true'
|
||||
@@ -66,87 +202,249 @@ class DiscourseClient(object):
|
||||
return self._put(url, **kwargs)
|
||||
|
||||
def pick_avatar(self, username, gravatar=True, generated=False, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
gravatar:
|
||||
generated:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
url = '/users/{0}/preferences/avatar/pick'.format(username)
|
||||
return self._put(url, **kwargs)
|
||||
|
||||
def update_email(self, username, email, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
email:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._put('/users/{0}/preferences/email'.format(username), email=email, **kwargs)
|
||||
|
||||
def update_user(self, username, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._put('/users/{0}'.format(username), **kwargs)
|
||||
|
||||
def update_username(self, username, new_username, **kwargs):
|
||||
return self._put('/users/{0}/preferences/username'.format(username), username=new_username, **kwargs)
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
new_username:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._put('/users/{0}/preferences/username'.format(username),
|
||||
username=new_username, **kwargs)
|
||||
|
||||
def set_preference(self, username=None, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
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
|
||||
"""
|
||||
|
||||
expect sso_secret, name, username, email, external_id, avatar_url,
|
||||
avatar_force_update
|
||||
|
||||
Args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
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):
|
||||
"""
|
||||
|
||||
Args:
|
||||
userid:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._post('/admin/users/{0}/generate_api_key'.format(userid), **kwargs)
|
||||
|
||||
def delete_user(self, userid, **kwargs):
|
||||
"""
|
||||
|
||||
block_email='true'
|
||||
block_ip='false'
|
||||
block_urls='false'
|
||||
|
||||
Args:
|
||||
userid:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._delete('/admin/users/{0}.json'.format(userid), **kwargs)
|
||||
|
||||
def users(self, filter=None, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
filter:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
if filter is None:
|
||||
filter = 'active'
|
||||
|
||||
return self._get('/admin/users/list/{0}.json'.format(filter), **kwargs)
|
||||
|
||||
def private_messages(self, username=None, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
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):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
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):
|
||||
"""
|
||||
|
||||
Args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get('/hot.json', **kwargs)
|
||||
|
||||
def latest_topics(self, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get('/latest.json', **kwargs)
|
||||
|
||||
def new_topics(self, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get('/new.json', **kwargs)
|
||||
|
||||
def topic(self, slug, topic_id, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
slug:
|
||||
topic_id:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get('/t/{0}/{1}.json'.format(slug, topic_id), **kwargs)
|
||||
|
||||
def post(self, topic_id, post_id, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
topic_id:
|
||||
post_id:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get('/t/{0}/{1}.json'.format(topic_id, post_id), **kwargs)
|
||||
|
||||
def posts(self, topic_id, post_ids=None, **kwargs):
|
||||
""" Get a set of posts from a topic
|
||||
"""
|
||||
Get a set of posts from a topic
|
||||
|
||||
Args:
|
||||
topic_id:
|
||||
post_ids: a list of post ids from the topic stream
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
post_ids: a list of post ids from the topic stream
|
||||
"""
|
||||
if post_ids:
|
||||
kwargs['post_ids[]'] = post_ids
|
||||
return self._get('/t/{0}/posts.json'.format(topic_id), **kwargs)
|
||||
|
||||
def topic_timings(self, topic_id, time, timings={}, **kwargs):
|
||||
""" Set time spent reading a post
|
||||
|
||||
time: overall time for the topic
|
||||
timings = { post_number: ms }
|
||||
"""
|
||||
Set time spent reading a post
|
||||
|
||||
A side effect of this is to mark the post as read
|
||||
|
||||
Args:
|
||||
topic_id: { post_number: ms }
|
||||
time: overall time for the topic (in what unit????)
|
||||
timings:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
kwargs['topic_id'] = topic_id
|
||||
kwargs['topic_time'] = time
|
||||
@@ -156,23 +454,68 @@ class DiscourseClient(object):
|
||||
return self._post('/topics/timings', **kwargs)
|
||||
|
||||
def topic_posts(self, topic_id, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
topic_id:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get('/t/{0}/posts.json'.format(topic_id), **kwargs)
|
||||
|
||||
def create_post(self, content, **kwargs):
|
||||
""" int: topic_id the topic to reply too
|
||||
"""
|
||||
|
||||
Args:
|
||||
content:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._post('/posts', raw=content, **kwargs)
|
||||
|
||||
def update_post(self, post_id, content, edit_reason='', **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
post_id:
|
||||
content:
|
||||
edit_reason:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
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):
|
||||
"""
|
||||
|
||||
Args:
|
||||
username:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
url = '/topics/created-by/{0}.json'.format(username)
|
||||
return self._get(url, **kwargs)['topic_list']['topics']
|
||||
|
||||
def invite_user_to_topic(self, user_email, topic_id):
|
||||
"""
|
||||
|
||||
Args:
|
||||
user_email:
|
||||
topic_id:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
kwargs = {
|
||||
'email': user_email,
|
||||
'topic_id': topic_id,
|
||||
@@ -180,13 +523,33 @@ class DiscourseClient(object):
|
||||
return self._post('/t/{0}/invite.json'.format(topic_id), **kwargs)
|
||||
|
||||
def search(self, term, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
term:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
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
|
||||
def create_category(self, name, color, text_color='FFFFFF',
|
||||
permissions=None, parent=None, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
name:
|
||||
color:
|
||||
text_color:
|
||||
permissions: dict of 'everyone', 'admins', 'moderators', 'staff' with values of ???
|
||||
parent:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
kwargs['name'] = name
|
||||
kwargs['color'] = color
|
||||
kwargs['text_color'] = text_color
|
||||
@@ -211,32 +574,104 @@ class DiscourseClient(object):
|
||||
return self._post('/categories', **kwargs)
|
||||
|
||||
def categories(self, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._get('/categories.json', **kwargs)['category_list']['categories']
|
||||
|
||||
def category(self, name, parent=None, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
name:
|
||||
parent:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
if parent:
|
||||
name = u'{0}/{1}'.format(parent, name)
|
||||
|
||||
return self._get(u'/category/{0}.json'.format(name), **kwargs)
|
||||
|
||||
def site_settings(self, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
for setting, value in kwargs.items():
|
||||
setting = setting.replace(' ', '_')
|
||||
self._request('PUT', '/admin/site_settings/{0}'.format(setting), {setting: value})
|
||||
|
||||
def _get(self, path, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
path:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._request('GET', path, kwargs)
|
||||
|
||||
def _put(self, path, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
path:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._request('PUT', path, kwargs)
|
||||
|
||||
def _post(self, path, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
path:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._request('POST', path, kwargs)
|
||||
|
||||
def _delete(self, path, **kwargs):
|
||||
"""
|
||||
|
||||
Args:
|
||||
path:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return self._request('DELETE', path, kwargs)
|
||||
|
||||
def _request(self, verb, path, params):
|
||||
"""
|
||||
|
||||
Args:
|
||||
verb:
|
||||
path:
|
||||
params:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
params['api_key'] = self.api_key
|
||||
if 'api_username' not in params:
|
||||
params['api_username'] = self.api_username
|
||||
@@ -264,13 +699,14 @@ class DiscourseClient(object):
|
||||
raise DiscourseServerError(msg, response=response)
|
||||
|
||||
if response.status_code == 302:
|
||||
raise DiscourseError('Unexpected Redirect, invalid api key or host?', response=response)
|
||||
raise DiscourseError(
|
||||
'Unexpected Redirect, invalid api key or host?', response=response)
|
||||
|
||||
json_content = 'application/json; charset=utf-8'
|
||||
content_type = response.headers['content-type']
|
||||
if content_type != json_content:
|
||||
# some calls return empty html documents
|
||||
if response.content == ' ':
|
||||
if not response.content.strip():
|
||||
return None
|
||||
|
||||
raise DiscourseError('Invalid Response, expecting "{0}" got "{1}"'.format(
|
||||
|
||||
+3
-3
@@ -2,11 +2,11 @@
|
||||
|
||||
import cmd
|
||||
import json
|
||||
import logging
|
||||
import optparse
|
||||
import os
|
||||
import pydoc
|
||||
import sys
|
||||
import os
|
||||
import logging
|
||||
|
||||
from pydiscourse.client import DiscourseClient, DiscourseError
|
||||
|
||||
@@ -31,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
|
||||
|
||||
|
||||
+6
-3
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
Utilities to implement Single Sign On for Discourse with a Python managed authentication DB
|
||||
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
|
||||
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
|
||||
|
||||
@@ -16,7 +18,8 @@ A SSO request handler might look something like
|
||||
except DiscourseError as e:
|
||||
return HTTP400(e.args[0])
|
||||
|
||||
url = sso_redirect_url(nonce, SECRET, request.user.email, request.user.id, request.user.username)
|
||||
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
|
||||
|
||||
+64
-4
@@ -1,8 +1,19 @@
|
||||
import sys
|
||||
import unittest
|
||||
import mock
|
||||
import requests
|
||||
|
||||
from pydiscourse import client
|
||||
|
||||
import sys
|
||||
if sys.version_info < (3,):
|
||||
def b(x):
|
||||
return x
|
||||
else:
|
||||
import codecs
|
||||
def b(x):
|
||||
return codecs.latin_1_encode(x)[0]
|
||||
|
||||
|
||||
def prepare_response(request):
|
||||
# we need to mocked response to look a little more real
|
||||
@@ -10,8 +21,12 @@ def prepare_response(request):
|
||||
|
||||
|
||||
class ClientBaseTestCase(unittest.TestCase):
|
||||
"""
|
||||
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
self.host = 'testhost'
|
||||
self.host = 'http://testhost'
|
||||
self.api_username = 'testuser'
|
||||
self.api_key = 'testkey'
|
||||
|
||||
@@ -31,6 +46,32 @@ class ClientBaseTestCase(unittest.TestCase):
|
||||
self.assertEqual(kwargs, params)
|
||||
|
||||
|
||||
|
||||
class TestClientRequests(ClientBaseTestCase):
|
||||
"""
|
||||
Tests for common request handling
|
||||
"""
|
||||
|
||||
@mock.patch('pydiscourse.client.requests')
|
||||
def test_empty_content_http_ok(self, mocked_requests):
|
||||
"""Empty content should not raise error
|
||||
|
||||
Critical to test against *bytestrings* rather than unicode
|
||||
"""
|
||||
mocked_response = mock.MagicMock()
|
||||
mocked_response.content = b(' ')
|
||||
mocked_response.status_code = 200
|
||||
mocked_response.headers = {"content-type": "text/plain; charset=utf-8"}
|
||||
|
||||
assert "content-type" in mocked_response.headers
|
||||
|
||||
mocked_requests.request = mock.MagicMock()
|
||||
mocked_requests.request.return_value = mocked_response
|
||||
|
||||
resp = self.client._request('GET', '/users/admin/1/unsuspend', {})
|
||||
self.assertIsNone(resp)
|
||||
|
||||
|
||||
@mock.patch('requests.request')
|
||||
class TestUser(ClientBaseTestCase):
|
||||
|
||||
@@ -59,7 +100,26 @@ class TestUser(ClientBaseTestCase):
|
||||
def test_update_username(self, request):
|
||||
prepare_response(request)
|
||||
self.client.update_username('someuser', 'newname')
|
||||
self.assertRequestCalled(request, 'PUT', '/users/someuser/preferences/username', username='newname')
|
||||
self.assertRequestCalled(request, 'PUT',
|
||||
'/users/someuser/preferences/username',
|
||||
username='newname')
|
||||
|
||||
def test_by_external_id(self, request):
|
||||
prepare_response(request)
|
||||
self.client.by_external_id(123)
|
||||
self.assertRequestCalled(request, 'GET',
|
||||
'/users/by-external/123')
|
||||
|
||||
def test_suspend_user(self, request):
|
||||
prepare_response(request)
|
||||
self.client.suspend(123, 1, "Testing")
|
||||
self.assertRequestCalled(request, 'PUT', '/admin/users/123/suspend',
|
||||
duration=1, reason="Testing")
|
||||
|
||||
def test_unsuspend_user(self, request):
|
||||
prepare_response(request)
|
||||
self.client.unsuspend(123)
|
||||
self.assertRequestCalled(request, 'PUT', '/admin/users/123/unsuspend')
|
||||
|
||||
|
||||
@mock.patch('requests.request')
|
||||
@@ -111,8 +171,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.client.users()
|
||||
self.assertRequestCalled(request, 'GET', '/admin/users/list/active.json')
|
||||
|
||||
@@ -32,8 +32,6 @@ class SSOTestCase(unittest.TestCase):
|
||||
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)
|
||||
@@ -52,8 +50,6 @@ class Test_sso_validate(SSOTestCase):
|
||||
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')
|
||||
|
||||
|
||||
@@ -5,3 +5,17 @@ envlist = py27, py34, py35, pypy, pypy3
|
||||
setenv =
|
||||
PYTHONPATH = {toxinidir}:{toxinidir}/pydiscourse
|
||||
commands = python setup.py test
|
||||
|
||||
[testenv:flake8]
|
||||
basepython=python
|
||||
deps=
|
||||
flake8
|
||||
flake8_docstrings
|
||||
commands=
|
||||
flake8 pydiscourse
|
||||
|
||||
[flake8]
|
||||
ignore = E126,E128
|
||||
max-line-length = 99
|
||||
exclude = .ropeproject
|
||||
max-complexity = 10
|
||||
|
||||
Reference in New Issue
Block a user