pandora/pandora/user/views.py

795 lines
26 KiB
Python
Raw Normal View History

2010-12-24 12:54:35 +00:00
# -*- coding: utf-8 -*-
2010-01-25 09:20:21 +00:00
# vi:si:et:sw=4:sts=4:ts=4
2010-12-24 12:54:35 +00:00
import random
random.seed()
2010-01-25 09:20:21 +00:00
from django.contrib.auth import authenticate, login, logout
2011-01-01 11:44:42 +00:00
from django.template import RequestContext, loader
2010-01-25 09:20:21 +00:00
from django.utils import simplejson as json
2010-02-06 08:24:39 +00:00
from django.conf import settings
2011-12-18 09:27:15 +00:00
from django.core.mail import send_mail, BadHeaderError, EmailMessage
2011-10-21 18:36:21 +00:00
from django.shortcuts import redirect
2013-03-03 15:06:22 +00:00
from django.db.models import Max
from django.contrib.auth.models import User, Group
2010-01-25 09:20:21 +00:00
from ox.django.shortcuts import render_to_json_response, json_response, get_object_or_404_json
from ox.django.decorators import login_required_json
2010-12-24 12:54:35 +00:00
import ox
2010-01-25 09:20:21 +00:00
from ox.django.api import actions
2011-01-25 14:45:07 +00:00
from item.models import Access, Item
from item import utils
import models
from decorators import capability_required_json
2010-02-27 10:37:00 +00:00
2011-01-03 12:31:50 +00:00
def signin(request):
2010-01-25 09:20:21 +00:00
'''
2013-03-04 19:35:06 +00:00
takes {
username: string,
password: string
}
2011-01-01 11:44:42 +00:00
2013-03-04 19:35:06 +00:00
returns {
errors: {
username: 'Unknown Username',
password: 'Incorrect Password'
}
user: {
...
}
}
2010-01-25 09:20:21 +00:00
'''
data = json.loads(request.POST['data'])
2011-10-22 12:27:00 +00:00
if 'username' in data and 'password' in data:
data['username'] = data['username'].strip()
if settings.AUTH_CHECK_USERNAME:
qs = User.objects.filter(username__iexact=data['username'])
if qs.count() == 0:
response = json_response({
'errors': {
'username': 'Unknown Username'
}
})
username = None
else:
username = qs[0].username
2010-01-25 09:20:21 +00:00
else:
username = data['username']
if username:
2011-12-18 10:05:35 +00:00
user = authenticate(username=username, password=data['password'])
if user is not None:
if user.is_active:
2011-10-09 13:39:31 +00:00
request.session['ui'] = '{}'
login(request, user)
2011-10-03 11:52:16 +00:00
user_json = models.init_user(user, request)
response = json_response({
'user': user_json
})
else:
response = json_response({
'errors': {
'username': 'User Disabled'
}
})
else:
response = json_response({
'errors': {
'password': 'Incorrect Password'
}
})
2010-01-25 09:20:21 +00:00
else:
2010-02-10 13:10:28 +00:00
response = json_response(status=400, text='invalid data')
2010-01-25 09:20:21 +00:00
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(signin, cache=False)
2010-01-25 09:20:21 +00:00
2011-01-01 11:44:42 +00:00
2011-01-03 12:31:50 +00:00
def signout(request):
2010-01-25 09:20:21 +00:00
'''
2013-03-04 19:35:06 +00:00
takes {}
2011-01-01 11:44:42 +00:00
2013-03-04 19:35:06 +00:00
returns {
user: {
default user
2010-12-25 04:19:37 +00:00
}
}
2010-01-25 09:20:21 +00:00
'''
2010-12-24 10:14:13 +00:00
response = json_response(text='ok')
2010-01-25 09:20:21 +00:00
if request.user.is_authenticated():
2012-07-01 10:27:06 +00:00
profile = request.user.get_profile()
if profile.ui.get('page') == 'signout':
profile.ui['page'] = ''
profile.save()
2010-12-24 10:14:13 +00:00
response = json_response(text='logged out')
logout(request)
2011-01-03 14:25:51 +00:00
2011-09-06 12:06:59 +00:00
response['data']['user'] = settings.CONFIG['user']
2010-01-25 09:20:21 +00:00
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(signout, cache=False)
2010-01-25 09:20:21 +00:00
2011-01-01 11:44:42 +00:00
2011-01-03 12:31:50 +00:00
def signup(request):
2010-01-25 09:20:21 +00:00
'''
2013-03-04 19:35:06 +00:00
takes {
username: string,
password: string,
email: string
}
2011-01-01 11:44:42 +00:00
2013-03-04 19:35:06 +00:00
returns {
errors: {
username: 'Unknown Username',
password: 'Incorrect Password'
}
user: {
...
}
}
2010-01-25 09:20:21 +00:00
'''
data = json.loads(request.POST['data'])
2011-10-22 12:27:00 +00:00
if 'username' in data and 'password' in data:
data['username'] = data['username'].strip()
if 'email' in data:
data['email'] = ox.escape_html(data['email'])
if User.objects.filter(username__iexact=data['username']).count() > 0:
response = json_response({
'errors': {
2010-12-24 10:14:13 +00:00
'username': 'Username already exists'
}
})
elif User.objects.filter(email__iexact=data['email']).count() > 0:
response = json_response({
'errors': {
2013-08-26 17:52:45 +00:00
'email': 'Email address already exists'
}
})
2011-10-22 12:27:00 +00:00
elif not data['password']:
2010-12-24 12:54:35 +00:00
response = json_response({
'errors': {
'password': 'Password can not be empty'
}
})
else:
first_user = User.objects.count() == 0
user = User(username=data['username'], email=data['email'])
2011-10-22 12:27:00 +00:00
user.set_password(data['password'])
#make first user admin
user.is_superuser = first_user
user.is_staff = first_user
2010-01-26 13:24:50 +00:00
user.save()
2011-01-11 10:18:18 +00:00
#create default user lists:
for l in settings.CONFIG['personalLists']:
list = models.List(name=l['title'], user=user)
2011-01-11 10:18:18 +00:00
for key in ('query', 'public', 'featured'):
if key in l:
setattr(list, key, l[key])
list.save()
2013-03-03 15:06:22 +00:00
pos = models.Position(list=list, section='personal', user=user)
qs = models.Position.objects.filter(user=user, section='personal')
pos.position = (qs.aggregate(Max('position'))['position__max'] or 0) + 1
pos.save()
if request.session.session_key:
models.SessionData.objects.filter(session_key=request.session.session_key).update(user=user)
ui = json.loads(request.session.get('ui', 'null'))
2011-10-22 12:27:00 +00:00
user = authenticate(username=data['username'],
password=data['password'])
if ui:
profile = user.get_profile()
profile.ui = ui
profile.save()
login(request, user)
2011-11-07 22:28:28 +00:00
user_json = models.init_user(user, request)
response = json_response({
'user': user_json
}, text='account created')
else:
response = json_response(status=400, text='invalid data')
2010-01-25 09:20:21 +00:00
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(signup, cache=False)
2010-01-25 09:20:21 +00:00
2011-01-01 11:44:42 +00:00
2010-12-24 12:54:35 +00:00
def resetPassword(request):
'''
2013-03-04 19:35:06 +00:00
takes {
username: string,
password: string,
code: string
2010-12-24 12:54:35 +00:00
}
2011-01-01 11:44:42 +00:00
2013-03-04 19:35:06 +00:00
returns {
errors: {
code: 'Incorrect Code'
}
user {
2010-12-24 12:54:35 +00:00
}
}
'''
data = json.loads(request.POST['data'])
2011-10-07 17:56:39 +00:00
if 'code' in data and 'password' in data:
2010-12-24 12:54:35 +00:00
if not data['password']:
response = json_response({
'errors': {
'password': 'Password can not be empty'
}
})
else:
2011-10-07 17:56:39 +00:00
qs = models.UserProfile.objects.filter(reset_code=data['code'])
2010-12-24 12:54:35 +00:00
if qs.count() == 1:
user = qs[0].user
user.set_password(data['password'])
user.save()
user_profile = user.get_profile()
2011-10-07 17:56:39 +00:00
user_profile.reset_code = None
2010-12-24 12:54:35 +00:00
user_profile.save()
user = authenticate(username=user.username, password=data['password'])
login(request, user)
2011-11-07 22:28:28 +00:00
user_json = models.init_user(user, request)
2010-12-24 12:54:35 +00:00
response = json_response({
'user': user_json
}, text='password reset')
else:
response = json_response({
'errors': {
2011-10-22 15:31:12 +00:00
'code': 'Incorrect code'
2010-12-24 12:54:35 +00:00
}
})
else:
response = json_response(status=400, text='invalid data')
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(resetPassword, cache=False)
2010-12-24 12:54:35 +00:00
2011-01-01 11:44:42 +00:00
2010-12-24 12:54:35 +00:00
def requestToken(request):
'''
2013-03-04 19:35:06 +00:00
takes {
username: string,
email: string
}
2011-01-01 11:44:42 +00:00
2013-03-04 19:35:06 +00:00
returns {
errors: {
username: 'Unknown Username'
email: 'Unknown Email'
}
2013-03-04 19:35:06 +00:00
username: user
}
'''
2010-01-25 09:20:21 +00:00
data = json.loads(request.POST['data'])
user = None
if 'username' in data:
try:
user = User.objects.get(username__iexact=data['username'])
except User.DoesNotExist:
user = None
elif 'email' in data:
try:
user = User.objects.get(email__iexact=data['email'])
except User.DoesNotExist:
user = None
if user:
while True:
2011-12-18 09:35:49 +00:00
code = ox.toAZ(random.randint(ox.fromAZ('AAAAAAAAAAAAAAAA'),
ox.fromAZ('AAAAAAAAAAAAAAAAA')))
2011-10-07 17:56:39 +00:00
if models.UserProfile.objects.filter(reset_code=code).count() == 0:
break
user_profile = user.get_profile()
2011-10-07 17:56:39 +00:00
user_profile.reset_code = code
user_profile.save()
2010-02-03 11:59:11 +00:00
template = loader.get_template('password_reset_email.txt')
context = RequestContext(request, {
2011-10-07 17:56:39 +00:00
'code': code,
'sitename': settings.SITENAME,
2011-12-18 09:27:15 +00:00
'footer': settings.CONFIG['site']['email']['footer'],
2011-11-12 18:43:23 +00:00
'url': request.build_absolute_uri('/'),
})
message = template.render(context)
2010-12-25 10:12:51 +00:00
subject = '%s - Reset Password' % settings.SITENAME
user.email_user(subject, message)
response = json_response({
'username': user.username
}, text='password reset email sent')
2010-01-25 09:20:21 +00:00
else:
response = json_response({
'errors': {
}
})
if 'username' in data:
response['data']['errors']['username'] = 'Unknown Username'
elif 'email' in data:
response['data']['errors']['email'] = 'Unknown Email'
else:
response = json_response(status=400, text='invalid data')
2010-01-25 09:20:21 +00:00
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(requestToken, cache=False)
2010-07-22 13:03:16 +00:00
2011-01-01 11:44:42 +00:00
@capability_required_json('canManageUsers')
2011-10-03 16:09:11 +00:00
def editUser(request):
'''
2013-03-04 19:35:06 +00:00
takes {
2011-10-03 16:09:11 +00:00
key: value
}
2011-10-03 19:19:35 +00:00
required key: id
2011-10-03 18:10:53 +00:00
optional keys: username, email, level, notes
2011-10-03 16:09:11 +00:00
2013-03-04 19:35:06 +00:00
returns {
2011-10-03 16:09:11 +00:00
}
'''
response = json_response()
2011-10-03 19:22:13 +00:00
data = json.loads(request.POST['data'])
user = get_object_or_404_json(User, pk=ox.fromAZ(data['id']))
2011-10-03 16:09:11 +00:00
profile = user.get_profile()
2011-10-03 18:10:53 +00:00
if 'disabled' in data:
user.is_active = not data['disabled']
2011-10-03 16:09:11 +00:00
if 'email' in data:
if 'email' in data:
data['email'] = ox.escape_html(data['email'])
if User.objects.filter(email__iexact=data['email']).exclude(id=user.id).count()>0:
2011-10-03 19:30:43 +00:00
response = json_response(status=403, text='email already in use')
return render_to_json_response(response)
2011-10-03 16:09:11 +00:00
user.email = data['email']
if 'level' in data:
profile.set_level(data['level'])
2011-10-03 18:10:53 +00:00
if 'notes' in data:
profile.notes = data['notes']
2011-12-18 09:27:15 +00:00
if 'newsletter' in data:
profile.newsletter = data['newsletter']
2012-01-13 09:47:18 +00:00
if 'groups' in data:
groups = data['groups']
if isinstance(groups, list):
groups = filter(lambda g: g.strip(), groups)
groups = [ox.escape_html(g) for g in groups]
2012-01-13 09:47:18 +00:00
user.groups.exclude(name__in=groups).delete()
current_groups = [g.name for g in user.groups.all()]
for g in filter(lambda g: g not in current_groups, groups):
group, created = Group.objects.get_or_create(name=g)
2012-01-13 09:47:18 +00:00
user.groups.add(group)
2011-10-03 19:19:35 +00:00
if 'username' in data:
if User.objects.filter(
2011-12-18 10:05:35 +00:00
username__iexact=data['username']).exclude(id=user.id).count()>0:
2011-10-03 19:30:43 +00:00
response = json_response(status=403, text='username already in use')
return render_to_json_response(response)
2011-10-03 19:19:35 +00:00
user.username = data['username']
2011-10-03 16:09:11 +00:00
user.save()
profile.save()
2011-11-07 14:25:16 +00:00
response['data'] = user.data.get().json()
2011-10-03 16:09:11 +00:00
return render_to_json_response(response)
actions.register(editUser, cache=False)
@capability_required_json('canManageUsers')
2011-10-03 16:09:11 +00:00
def removeUser(request):
'''
2013-03-04 19:35:06 +00:00
takes {
2011-10-03 16:09:11 +00:00
username: username
}
2013-03-04 19:35:06 +00:00
returns {}
2011-10-03 16:09:11 +00:00
'''
response = json_response()
data = json.load(request.POST['data'])
user = get_object_or_404_json(User, username=data['username'])
2011-10-03 16:09:11 +00:00
user.delete()
return render_to_json_response(response)
actions.register(removeUser, cache=False)
def findUser(request):
2010-07-22 13:03:16 +00:00
'''
2013-03-04 19:35:06 +00:00
takes {
key: string, //username, email
value: string,
operator: "==" // "==", "="
keys: [string]
}
2011-01-01 11:44:42 +00:00
2013-03-04 19:35:06 +00:00
returns {
users: [object]
2010-07-22 13:03:16 +00:00
}
'''
data = json.loads(request.POST['data'])
response = json_response(status=200, text='ok')
2011-10-03 11:52:16 +00:00
#keys = data.get('keys')
#if not keys:
# keys = ['username', 'level']
keys = ['username', 'level']
2011-08-23 17:39:34 +00:00
if settings.AUTH_CHECK_USERNAME:
if data['key'] == 'email':
response['data']['users'] = [models.user_json(u, keys)
for u in User.objects.filter(email__iexact=data['value'])]
else:
response['data']['users'] = [models.user_json(u, keys)
for u in User.objects.filter(username__iexact=data['value'])]
2010-12-25 04:19:37 +00:00
else:
response['data']['users'] = [{'username': data['value'], 'level': 'member'}]
2010-07-22 13:03:16 +00:00
return render_to_json_response(response)
actions.register(findUser)
2010-01-25 09:20:21 +00:00
2011-01-01 11:44:42 +00:00
def parse_query(data, user):
query = {}
query['range'] = [0, 100]
query['sort'] = [{'key':'name', 'operator':'+'}]
for key in ('keys', 'range', 'sort', 'query'):
if key in data:
query[key] = data[key]
2011-11-07 14:25:16 +00:00
query['qs'] = models.SessionData.objects.find(query, user)
return query
def order_query(qs, sort):
order_by = []
for e in sort:
operator = e['operator']
if operator != '-':
operator = ''
key = {
2011-12-03 16:52:48 +00:00
'browser': 'browser',
2011-11-07 14:25:16 +00:00
'email': 'user__email',
'firstseen': 'firstseen',
'groups': 'groupssort',
2011-11-07 14:25:16 +00:00
'ip': 'ip',
'lastseen': 'lastseen',
2011-12-03 16:52:48 +00:00
'level': 'level',
'location': 'location_sort',
2011-11-07 14:25:16 +00:00
'screensize': 'screensize',
2011-12-03 16:52:48 +00:00
'system': 'system',
2011-11-07 14:25:16 +00:00
'timesseen': 'timesseen',
'useragent': 'useragent',
2011-10-03 11:52:16 +00:00
'username': 'username',
'numberoflists': 'numberoflists',
2011-11-07 14:25:16 +00:00
'windowsize': 'windowsize',
}.get(e['key'], 'user__profile__%s'%e['key'])
order = '%s%s' % (operator, key)
order_by.append(order)
if order_by:
2011-11-07 14:25:16 +00:00
qs = qs.order_by(*order_by, nulls_last=True)
return qs
@capability_required_json('canManageUsers')
def findUsers(request):
'''
2013-03-04 19:35:06 +00:00
takes {
query: {
conditions: [
{
key: 'user',
value: 'something',
operator: '='
}
]
operator: ","
},
sort: [{key: 'username', operator: '+'}],
range: [0, 100]
keys: []
}
possible query keys:
username, email, lastLogin, browser
2013-03-04 19:35:06 +00:00
returns {
items: [
{name:, user:, featured:, public...}
]
}
takes {
query: query,
sort: array,
range: array
}
query: query object, more on query syntax at
https://wiki.0x2620.org/wiki/pandora/QuerySyntax
sort: array of key, operator dics
[
{
key: "year",
operator: "-"
},
{
key: "director",
operator: ""
}
]
range: result range, array [from, to]
with keys, items is list of dicts with requested properties:
2013-03-04 19:35:06 +00:00
returns {
items: [object]
}
Positions
2013-03-04 19:35:06 +00:00
takes {
query: query,
positions: []
}
query: query object, more on query syntax at
https://wiki.0x2620.org/wiki/pandora/QuerySyntax
positions: ids of places for which positions are required
'''
2011-10-03 11:52:16 +00:00
response = json_response(status=200, text='ok')
data = json.loads(request.POST['data'])
query = parse_query(data, request.user)
2011-10-03 11:52:16 +00:00
qs = order_query(query['qs'], query['sort'])
if 'keys' in data:
qs = qs[query['range'][0]:query['range'][1]]
2011-11-07 14:25:16 +00:00
response['data']['items'] = [p.json(data['keys'], request.user) for p in qs]
elif 'position' in query:
ids = [i.get_id() for i in qs]
data['conditions'] = data['conditions'] + {
'value': data['position'],
'key': query['sort'][0]['key'],
'operator': '^'
}
query = parse_query(data, request.user)
qs = order_query(query['qs'], query['sort'])
if qs.count() > 0:
response['data']['position'] = utils.get_positions(ids, [qs[0].itemId])[0]
elif 'positions' in data:
2011-11-07 23:00:08 +00:00
ids = [i.get_id() for i in qs]
response['data']['positions'] = utils.get_positions(ids, data['positions'])
else:
response['data']['items'] = qs.count()
2011-11-07 14:46:16 +00:00
response['data']['users'] = qs.exclude(user=None).count()
2012-03-30 14:34:33 +00:00
response['data']['robots'] = qs.filter(level=-1).count()
response['data']['guests'] = qs.filter(level=0).count()
return render_to_json_response(response)
actions.register(findUsers)
2011-12-18 09:27:15 +00:00
@login_required_json
def mail(request):
'''
2013-03-04 19:35:06 +00:00
takes {
to: [string], // array of usernames to send mail to
subject: string,
message: string
2011-12-18 09:27:15 +00:00
}
message can contain {username} or {email},
this will be replace with the user/email
the mail is sent to.
2013-03-04 19:35:06 +00:00
returns {
2011-12-18 09:27:15 +00:00
}
'''
response = json_response()
data = json.loads(request.POST['data'])
p = request.user.get_profile()
if p.capability('canSendMail'):
email_from = '"%s" <%s>' % (settings.SITENAME, settings.CONFIG['site']['email']['system'])
headers = {
'Reply-To': settings.CONFIG['site']['email']['contact']
}
subject = data.get('subject', '').strip()
users = [User.objects.get(username=username) for username in data['to']]
2011-12-18 09:27:15 +00:00
for user in users:
if user.email:
message = data['message']
for key, value in (
('{username}', user.username),
('{email}', user.email),
):
message = message.replace(key, value)
email_to = '"%s" <%s>' % (user.username, user.email)
email = EmailMessage(subject,
message,
email_from,
[email_to],
headers = headers)
email.send(fail_silently=True)
if 'receipt' in data \
and data['receipt']:
template = loader.get_template('mailout_receipt.txt')
context = RequestContext(request, {
'footer': settings.CONFIG['site']['email']['footer'],
'to': ', '.join(['"%s" <%s>' % (u.username, u.email) for u in users]),
'subject': subject,
'message': data['message'],
'url': request.build_absolute_uri('/'),
})
message = template.render(context)
subject = u'Fwd: %s' % subject
email_to = '"%s" <%s>' % (request.user.username, request.user.email)
receipt = EmailMessage(subject,
message,
email_from,
[email_to])
receipt.send(fail_silently=True)
response = json_response(text='message sent')
else:
response = json_response(status=403, text='not allowed to send mail')
return render_to_json_response(response)
actions.register(mail, cache=False)
def contact(request):
2010-02-16 10:10:53 +00:00
'''
2013-03-04 19:35:06 +00:00
takes {
email: string,
subject: string,
message: string
}
2011-01-01 11:44:42 +00:00
2013-03-04 19:35:06 +00:00
returns {
}
2010-02-16 10:10:53 +00:00
'''
data = json.loads(request.POST['data'])
2011-11-02 13:05:30 +00:00
name = data.get('name', '')
email = data.get('email', '')
if request.user.is_authenticated():
if not name:
name = request.user.username
if not email:
email = request.user.email
if 'message' in data and data['message'].strip():
2011-12-18 09:27:15 +00:00
email_from = '"%s" <%s>' % (settings.SITENAME, settings.CONFIG['site']['email']['system'])
2011-11-02 13:05:30 +00:00
email_to = [settings.CONFIG['site']['email']['contact'], ]
2011-11-12 18:43:23 +00:00
subject = data.get('subject', '').strip()
2010-02-16 10:10:53 +00:00
template = loader.get_template('contact_email.txt')
context = RequestContext(request, {
2011-11-12 18:43:23 +00:00
'name': name,
2010-02-16 10:10:53 +00:00
'email': email,
2011-11-12 19:43:58 +00:00
'subject': subject,
2011-11-02 13:05:30 +00:00
'message': data['message'].strip(),
'sitename': settings.SITENAME,
2011-12-18 09:27:15 +00:00
'footer': settings.CONFIG['site']['email']['footer'],
2011-11-12 18:43:23 +00:00
'url': request.build_absolute_uri('/'),
2010-02-16 10:10:53 +00:00
})
2012-05-27 11:52:12 +00:00
subject = ox.decode_html(subject)
message = ox.decode_html(template.render(context))
2010-02-16 10:10:53 +00:00
response = json_response(text='message sent')
try:
2011-12-18 09:27:15 +00:00
send_mail(u'%s Contact - %s' % (settings.SITENAME, subject), message, email_from, email_to)
2010-02-16 10:10:53 +00:00
except BadHeaderError:
response = json_response(status=400, text='invalid data')
2011-11-02 13:05:30 +00:00
if request.user.is_authenticated() \
and 'receipt' in data \
and data['receipt']:
2011-11-02 16:09:59 +00:00
template = loader.get_template('contact_receipt.txt')
context = RequestContext(request, {
'name': name,
2011-11-12 18:43:23 +00:00
'from': email,
2011-11-02 16:09:59 +00:00
'sitename': settings.SITENAME,
2011-12-18 09:27:15 +00:00
'footer': settings.CONFIG['site']['email']['footer'],
2011-11-12 19:46:43 +00:00
'to': email_to[0],
2011-11-12 18:43:23 +00:00
'subject': subject,
'message': data['message'].strip(),
'url': request.build_absolute_uri('/'),
2011-11-02 16:09:59 +00:00
})
message = template.render(context)
2011-11-02 13:05:30 +00:00
try:
2011-11-12 18:43:23 +00:00
send_mail('Fwd: %s' % subject, message, email_from, [email])
2011-11-02 13:05:30 +00:00
except:
pass
2010-02-16 10:10:53 +00:00
else:
response = json_response(status=400, text='invalid data')
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(contact, cache=False)
2010-02-16 10:10:53 +00:00
2011-01-01 11:44:42 +00:00
2011-01-11 11:51:09 +00:00
def getPositionById(list, key):
for i in range(0, len(list)):
if list[i]['id'] == key:
return i
return -1
2010-01-25 09:20:21 +00:00
@login_required_json
2011-10-18 21:41:54 +00:00
def editPreferences(request):
2010-01-25 09:20:21 +00:00
'''
2013-03-04 19:35:06 +00:00
takes {
2011-10-18 21:41:54 +00:00
key: value
2011-01-11 11:51:09 +00:00
}
2011-10-18 21:41:54 +00:00
keys: email, password
2013-03-04 19:35:06 +00:00
returns {}
2010-01-25 09:20:21 +00:00
'''
2011-01-11 11:51:09 +00:00
data = json.loads(request.POST['data'])
2011-10-18 21:41:54 +00:00
errors = {}
change = False
2010-02-10 13:10:28 +00:00
response = json_response()
2011-10-18 21:41:54 +00:00
if 'email' in data:
if User.objects.filter(
2011-10-18 21:41:54 +00:00
email=data['email']).exclude(username=request.user.username).count()>0:
errors['email'] = 'Email address already in use'
else:
change = True
request.user.email = ox.escape_html(data['email'])
2011-12-18 09:27:15 +00:00
if 'newsletter' in data:
profile = request.user.get_profile()
profile.newsletter = data['newsletter']
profile.save()
2011-10-18 21:41:54 +00:00
if 'password' in data:
change = True
request.user.set_password(data['password'])
2011-10-18 21:41:54 +00:00
if change:
request.user.save()
if errors:
response = json_response({ 'errors': errors})
2010-01-25 09:20:21 +00:00
return render_to_json_response(response)
2011-10-18 21:41:54 +00:00
actions.register(editPreferences, cache=False)
2011-01-11 10:18:18 +00:00
2011-10-21 18:36:21 +00:00
def reset_ui(request):
if request.user.is_authenticated():
profile = request.user.get_profile()
profile.ui = {}
profile.save()
else:
request.session['ui'] = '{}'
return redirect('/')
2011-01-15 23:26:39 +00:00
def resetUI(request):
'''
reset user ui settings to defaults
2013-03-04 19:35:06 +00:00
takes {
2011-01-15 23:26:39 +00:00
}
2013-03-04 19:35:06 +00:00
returns {
2011-01-15 23:26:39 +00:00
}
'''
response = json_response()
2011-10-09 13:39:31 +00:00
if request.user.is_authenticated():
profile = request.user.get_profile()
profile.ui = {}
profile.save()
else:
request.session['ui'] = '{}'
2011-01-15 23:26:39 +00:00
return render_to_json_response(response)
actions.register(resetUI, cache=False)
2011-01-11 10:18:18 +00:00
def setUI(request):
'''
2013-03-04 19:35:06 +00:00
takes {
2011-01-11 11:51:09 +00:00
key.subkey: value
}
2011-01-11 14:56:08 +00:00
you can set nested keys
2011-01-15 14:22:29 +00:00
api.setUI({"lists|my|ListView": "icons"})
2011-01-11 14:56:08 +00:00
2013-03-04 19:35:06 +00:00
returns {
2011-01-11 14:56:08 +00:00
}
2011-01-11 10:18:18 +00:00
'''
data = json.loads(request.POST['data'])
2011-01-25 14:45:07 +00:00
if request.user.is_authenticated():
2011-02-22 10:44:17 +00:00
profile = request.user.get_profile()
2011-10-09 13:39:31 +00:00
ui = profile.ui
else:
ui = json.loads(request.session.get('ui', '{}'))
for key in data:
keys = map(lambda p: p.replace('\0', '\\.'), key.replace('\\.', '\0').split('.'))
2011-10-09 13:39:31 +00:00
value = data[key]
p = ui
while len(keys)>1:
key = keys.pop(0)
if isinstance(p, list):
p = p[getPositionById(p, key)]
2011-08-25 16:12:36 +00:00
else:
2011-10-09 13:39:31 +00:00
if key not in p:
p[key] = {}
p = p[key]
if value == None and keys[0] in p:
del p[keys[0]]
else:
p[keys[0]] = value
if request.user.is_authenticated():
2011-01-25 14:45:07 +00:00
profile.save()
2011-10-09 13:39:31 +00:00
else:
request.session['ui'] = json.dumps(ui)
2011-01-25 14:45:07 +00:00
if data.get('item'):
item = get_object_or_404_json(Item, itemId=data['item'])
2011-01-25 14:45:07 +00:00
if request.user.is_authenticated():
access, created = Access.objects.get_or_create(item=item, user=request.user)
2011-01-11 11:51:09 +00:00
else:
2011-01-25 14:45:07 +00:00
access, created = Access.objects.get_or_create(item=item, user=None)
2011-11-11 13:04:15 +00:00
if not created:
access.save()
2011-01-25 14:45:07 +00:00
2011-01-11 10:18:18 +00:00
response = json_response()
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(setUI, cache=False)
2011-01-11 10:18:18 +00:00