cablegates/pandora/user/views.py

477 lines
14 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
2010-02-03 12:05:38 +00:00
from django import forms
2010-01-25 09:20:21 +00:00
from django.contrib.auth.models import User
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
2010-02-16 10:10:53 +00:00
from django.core.mail import send_mail, BadHeaderError
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
import models
from api.actions import actions
2011-01-03 14:25:51 +00:00
from app.models import site_config
2011-01-25 14:45:07 +00:00
from item.models import Access, Item
2010-02-27 10:37:00 +00:00
2011-01-03 12:31:50 +00:00
class SigninForm(forms.Form):
username = forms.TextInput()
password = forms.TextInput()
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 signin(request):
2010-01-25 09:20:21 +00:00
'''
param data {
username: 'username',
password: 'password'
}
2011-01-01 11:44:42 +00:00
return {
2010-12-25 04:19:37 +00:00
status: {'code': 200, 'text': 'ok'}
data: {
errors: {
2010-12-24 10:14:13 +00:00
username: 'Unknown Username',
password: 'Incorrect Password'
}
user: {
...
}
}
}
2010-01-25 09:20:21 +00:00
'''
data = json.loads(request.POST['data'])
2011-01-03 12:31:50 +00:00
form = SigninForm(data, request.FILES)
if form.is_valid():
if models.User.objects.filter(username=form.data['username']).count() == 0:
response = json_response({
'errors': {
2010-12-24 10:14:13 +00:00
'username': 'Unknown Username'
}
})
2010-01-25 09:20:21 +00:00
else:
user = authenticate(username=data['username'], password=data['password'])
if user is not None:
if user.is_active:
login(request, user)
user_json = models.get_user_json(user)
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
'''
param data {
}
2011-01-01 11:44:42 +00:00
return {
status: {'code': int, 'text': string}
2010-12-25 04:19:37 +00:00
data: {
user: {
default user
}
}
}
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():
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-01-14 14:32:48 +00:00
response['data']['user'] = site_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
class SignupForm(forms.Form):
username = forms.TextInput()
password = forms.TextInput()
email = forms.TextInput()
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
'''
param data {
username: 'username',
password: 'password',
email: 'emailaddress'
}
2011-01-01 11:44:42 +00:00
return {
status: {'code': int, 'text': string}
data: {
errors: {
2010-12-24 10:14:13 +00:00
username: 'Unknown Username',
password: 'Incorrect Password'
}
user: {
...
}
}
}
2010-01-25 09:20:21 +00:00
'''
data = json.loads(request.POST['data'])
2011-01-03 12:31:50 +00:00
form = SignupForm(data, request.FILES)
if form.is_valid():
if models.User.objects.filter(username=form.data['username']).count() > 0:
response = json_response({
'errors': {
2010-12-24 10:14:13 +00:00
'username': 'Username already exists'
}
})
elif models.User.objects.filter(email=form.data['email']).count() > 0:
response = json_response({
'errors': {
2010-12-24 10:14:13 +00:00
'email': 'Email address already exits'
}
})
2010-12-24 12:54:35 +00:00
elif not form.data['password']:
response = json_response({
'errors': {
'password': 'Password can not be empty'
}
})
else:
first_user = models.User.objects.count() == 0
user = models.User(username=form.data['username'], email=form.data['email'])
user.set_password(form.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.DEFAULT_LISTS:
list = models.List(name=l['name'], user=user)
for key in ('query', 'public', 'featured'):
if key in l:
setattr(list, key, l[key])
list.save()
user = authenticate(username=form.data['username'],
password=form.data['password'])
login(request, user)
user_json = models.get_user_json(user)
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):
'''
param data {
token: reset token
password: new password
}
2011-01-01 11:44:42 +00:00
2010-12-24 12:54:35 +00:00
return {
status: {'code': int, 'text': string}
data: {
errors: {
token: 'Invalid token'
}
user {
}
}
}
'''
data = json.loads(request.POST['data'])
if 'token' in data and 'password' in data:
if not data['password']:
response = json_response({
'errors': {
'password': 'Password can not be empty'
}
})
else:
qs = models.UserProfile.objects.filter(reset_token=data['token'])
if qs.count() == 1:
user = qs[0].user
user.set_password(data['password'])
user.save()
user_profile = user.get_profile()
user_profile.reset_token = None
user_profile.save()
user = authenticate(username=user.username, password=data['password'])
login(request, user)
user_json = models.get_user_json(user)
response = json_response({
'user': user_json
}, text='password reset')
else:
response = json_response({
'errors': {
'token': 'Invalid token'
}
})
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):
'''
param data {
username: username,
email: email
}
2011-01-01 11:44:42 +00:00
return {
status: {'code': int, 'text': string}
data: {
errors: {
username: 'Unknown Username'
email: 'Unknown Email'
}
2010-12-24 12:54:35 +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 = models.User.objects.get(username=data['username'])
except models.User.DoesNotExist:
user = None
elif 'email' in data:
try:
user = models.User.objects.get(email=data['email'])
except models.User.DoesNotExist:
user = None
if user:
while True:
token = ox.to32(random.randint(32768, 1048575))
if models.UserProfile.objects.filter(reset_token=token).count() == 0:
break
user_profile = user.get_profile()
user_profile.reset_token = token
user_profile.save()
2010-02-03 11:59:11 +00:00
template = loader.get_template('password_reset_email.txt')
context = RequestContext(request, {
'url': request.build_absolute_uri("/"),
'token': token,
'sitename': settings.SITENAME,
})
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
def findUser(request):
2010-07-22 13:03:16 +00:00
'''
param data {
key: "username",
value: "foo", operator: "="
2011-08-23 17:39:34 +00:00
keys: []
}
2011-01-01 11:44:42 +00:00
2010-07-22 13:03:16 +00:00
return {
'status': {'code': int, 'text': string}
'data': {
2011-08-23 17:39:34 +00:00
users = [{username: 'user1', level: ...}, {username: 'user2', ..}]
2010-07-22 13:03:16 +00:00
}
}
'''
#FIXME: support other operators and keys
data = json.loads(request.POST['data'])
response = json_response(status=200, text='ok')
2011-08-23 17:39:34 +00:00
keys = data.get('keys')
if not keys:
keys = ['username', 'level']
def user_json(user, keys):
return {
'usernname': user.username,
'level': user.get_profile().get_level()
}
2010-12-25 04:19:37 +00:00
if data['key'] == 'email':
2011-08-23 17:39:34 +00:00
response['data']['users'] = [user_json(u, keys)
for u in User.objects.filter(email__iexact=data['value'])]
2010-12-25 04:19:37 +00:00
else:
2011-08-23 17:39:34 +00:00
response['data']['users'] = [user_json(u, keys)
for u in User.objects.filter(username__iexact=data['value'])]
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
2010-02-16 10:10:53 +00:00
class ContactForm(forms.Form):
email = forms.EmailField()
subject = forms.TextInput()
message = forms.TextInput()
2011-01-01 11:44:42 +00:00
def contact(request):
2010-02-16 10:10:53 +00:00
'''
param data {
'email': string,
'message': string
}
2011-01-01 11:44:42 +00:00
return {
'status': {'code': int, 'text': string}
}
2010-02-16 10:10:53 +00:00
'''
data = json.loads(request.POST['data'])
form = ContactForm(data, request.FILES)
if form.is_valid():
email = data['email']
template = loader.get_template('contact_email.txt')
context = RequestContext(request, {
'sitename': settings.SITENAME,
'email': email,
'message': data['message'],
})
message = template.render(context)
subject = '%s contact: %s' % (settings.SITENAME, data['subject'])
response = json_response(text='message sent')
try:
send_mail(subject, message, email, [settings.DEFAULT_FROM_EMAIL, ])
except BadHeaderError:
response = json_response(status=400, text='invalid data')
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-01-11 11:51:09 +00:00
def setPreferences(request):
2010-01-25 09:20:21 +00:00
'''
2011-01-11 11:51:09 +00:00
param data {
key.subkey: value
}
return
2010-01-25 09:20:21 +00:00
'''
2011-01-11 11:51:09 +00:00
data = json.loads(request.POST['data'])
keys = data.keys()[0].split('.')
value = data.values()[0]
profile = request.user.get_profile()
p = profile.preferences
while len(keys)>1:
key = keys.pop(0)
if isinstance(p, list):
p = p[getPositionById(p, key)]
else:
p = p[key]
p[keys[0]] = value
profile.save()
2010-02-10 13:10:28 +00:00
response = json_response()
2010-01-25 09:20:21 +00:00
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(setPreferences, cache=False)
2011-01-11 10:18:18 +00:00
2011-01-15 23:26:39 +00:00
@login_required_json
def resetUI(request):
'''
reset user ui settings to defaults
param data {
}
return {
'status': {'code': int, 'text': string}
}
'''
profile = request.user.get_profile()
profile.ui = {}
profile.save()
response = json_response()
return render_to_json_response(response)
actions.register(resetUI, cache=False)
2011-01-11 10:18:18 +00:00
def setUI(request):
'''
2011-01-11 11:51:09 +00:00
param data {
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
return {
'status': {'code': int, 'text': string}
}
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-01-25 14:45:07 +00:00
for key in data:
keys = key.split('|')
value = data[key]
p = profile.ui
while len(keys)>1:
key = keys.pop(0)
if isinstance(p, list):
p = p[getPositionById(p, key)]
else:
if key not in p:
p[key] = {}
p = p[key]
p[keys[0]] = value
profile.save()
if data.get('item', False):
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)
access.save()
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