Skip to content

Commit

Permalink
#209 Impacts on create / edit user
Browse files Browse the repository at this point in the history
  • Loading branch information
tonylampada committed Sep 3, 2014
1 parent f34f2c2 commit 5f4cce0
Show file tree
Hide file tree
Showing 9 changed files with 148 additions and 69 deletions.
10 changes: 7 additions & 3 deletions djangoproject/core/middlewares.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ def process_request(self, request):
'core.views.user_views.editUserForm',
'core.views.user_views.editUser',
]
_paths = [reverse(v) for v in whitelist]
if request.path in _paths:
return None
whitelist2 = [
'/core/json/check_username_availability'
]
_paths = [reverse(v) for v in whitelist] + whitelist2
for p in _paths:
if p in request.path:
return None

messages.info(request, 'Please complete your profile before proceeding.')
url = reverse('core.views.user_views.editUserForm')
Expand Down
3 changes: 3 additions & 0 deletions djangoproject/core/services/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class FSException(Exception):
def __init__(self, message):
super(FSException, self).__init__(message)
18 changes: 14 additions & 4 deletions djangoproject/core/services/user_services.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from core.services import paypal_services, mail_services
from core.services import paypal_services, mail_services, FSException
from emailmgr import utils as emailmgr_utils
from emailmgr.models import EmailAddress
from core.models import *
Expand Down Expand Up @@ -33,8 +33,9 @@ def edit_existing_user(user, dict):
# userinfo.screenName = dict['screenName']
first_time = userinfo.date_last_updated == userinfo.date_created
if first_time:
pass
#TODO: change username
new_username = dict['username']
if new_username != user.username:
change_username(user, new_username)
now = timezone.now()
userinfo.website = dict['website']
userinfo.about = dict['about']
Expand Down Expand Up @@ -88,13 +89,22 @@ def is_username_available(username):


def change_username(user, new_username):
can_change = user.getUserInfo().can_change_username
if not can_change:
raise FSException('You cannot change your username anymore.')
if not is_valid_username(new_username):
raise FSException('Sorry, this username is invalid.')
if not is_username_available(new_username):
return False
raise FSException('Sorry, that username is already taken.')
old_username = user.username
user.username = new_username
user.save()
userinfo = user.getUserInfo()
userinfo.can_change_username = False
userinfo.save()
subject = 'user %s changed username %s --> %s' % (user.id, old_username, new_username)
body = '<a href="http://freedomsponsors.org/user/%s">%s</a>' % (user.id, new_username)
mail_services.notify_admin(subject, body)
return True


Expand Down
8 changes: 4 additions & 4 deletions djangoproject/core/urls/user_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

urlpatterns = patterns('core.views.user_views',
url(r'^$', 'listUsers'),
url(r'^(?P<user_id>\d+)/$', 'viewUserById'),
url(r'^(?P<user_id>\d+)/(?P<user_slug>.*)$', 'viewUserById'),
url(r'^(?P<username>\w+)/$', 'viewUserByUsername'),
url(r'^edit$', 'editUserForm'),
url(r'^edit/submit$', 'editUser'),
url(r'^cancel_account$', 'cancel_account'),
# url(r'^change_username', 'change_username'),
url(r'^change_username', 'change_username'),
url(r'^(?P<user_id>\d+)/$', 'viewUserById'),
url(r'^(?P<user_id>\d+)/(?P<user_slug>.*)$', 'viewUserById'),
url(r'^(?P<username>\w+)/$', 'viewUserByUsername'),
)
23 changes: 20 additions & 3 deletions djangoproject/core/views/json_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,26 @@ def latest_activity(request):

@login_required
def check_username_availability(request, username):
result = {'is_valid': user_services.is_valid_username(username)}
if result['is_valid']:
result['is_available'] = user_services.is_username_available(username)
if username == request.user.username:
result = {
'ok': False,
'message': '"%s" is already your current username!' % username
}
elif not user_services.is_valid_username(username):
result = {
'ok': False,
'message': 'Sorry! "%s" is not a valid username (should be alphanumeric).' % username
}
elif not user_services.is_username_available(username):
result = {
'ok': False,
'message': 'Sorry, "%s" is already taken.' % username
}
else:
result = {
'ok': True,
'message': 'Great! "%s" is available!' % username
}
return HttpResponse(json.dumps(result))


Expand Down
66 changes: 29 additions & 37 deletions djangoproject/core/views/user_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,24 @@
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, redirect
from django.utils.translation import ugettext as _
from core.services import user_services, mail_services
from core.services import user_services, mail_services, FSException
from django.conf import settings


def _view_user(request, user):
def viewUserById(request, user_id, user_slug=None):
try:
user = User.objects.get(pk=user_id)
except:
return HttpResponse(status=404, content='User not found')

return redirect('/user/%s' % user.username, permanent=True)

def viewUserByUsername(request, username):
try:
user = User.objects.get(username=username)
except:
return HttpResponse(status=404, content='User not found')

if not user.is_active and not request.user.is_superuser:
return render_to_response(
'core2/user_inactive.html',
Expand Down Expand Up @@ -40,23 +53,6 @@ def _view_user(request, user):
)


def viewUserById(request, user_id, user_slug=None):
try:
user = User.objects.get(pk=user_id)
except:
return HttpResponse(status=404, content='User not found')

return _view_user(request, user)

def viewUserByUsername(request, username):
try:
user = User.objects.get(username=username)
except:
return HttpResponse(status=404, content='User not found')

return _view_user(request, user)


@login_required
def editUserForm(request):
userinfo = request.user.getUserInfo()
Expand All @@ -70,8 +66,11 @@ def editUserForm(request):
userinfo.save()
mail_services.welcome(request.user)
_notify_admin_new_user(request.user)
first_time = userinfo.date_last_updated == userinfo.date_created

return render_to_response('core2/useredit.html', {
'userinfo': userinfo,
'can_edit_username': first_time,
'available_languages': available_languages,
'next': request.GET.get('next', '')},
context_instance=RequestContext(request)
Expand All @@ -85,7 +84,11 @@ def _notify_admin_new_user(user):

@login_required
def editUser(request):
paypalActivation, primaryActivation = user_services.edit_existing_user(request.user, request.POST)
try:
paypalActivation, primaryActivation = user_services.edit_existing_user(request.user, request.POST)
except FSException as e:
messages.error(request, e.message)
return redirect('/user/edit')

next = request.POST.get(_('next'))
if next:
Expand Down Expand Up @@ -130,23 +133,12 @@ def cancel_account(request):
def change_username(request):
can_change = request.user.getUserInfo().can_change_username
if request.method.lower() == 'post':
if can_change:
old_username = request.user.username
new_username = request.POST['new_username']
if not user_services.is_valid_username(new_username):
messages.error(request, 'Sorry, this username is invalid')
else:
change_ok = user_services.change_username(request.user, new_username)
if change_ok:
messages.info(request, 'Your username has been changed')
can_change = False
subject = 'user %s changed username %s --> %s' % (request.user.id, old_username, new_username)
body = '<a href="http://freedomsponsors.org/user/%s">%s</a>' % (request.user.id, new_username)
mail_services.notify_admin(subject, body)
else:
messages.error(request, 'Sorry, that username is already taken')
else:
messages.warning(request, 'You cannot change your username anymore')
new_username = request.POST['new_username']
try:
user_services.change_username(request.user, new_username)
messages.info(request, 'Your username has been changed')
except FSException as e:
messages.error(request, e.message)
return render_to_response(
'core2/change_username.html',
{'can_change': can_change},
Expand Down
13 changes: 2 additions & 11 deletions djangoproject/templates/core2/change_username.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,8 @@
var new_username = $scope.new_username;
FSApi.check_username_availability(new_username).onResult(function(result){
$scope.$apply(function(){
if(!result.is_valid){
$scope.available = false;
$scope.message = 'Sorry! "'+new_username+'" is not a valid username (should be alphanumeric).'
} else if(!result.is_available){
$scope.available = false;
$scope.message = 'Sorry, "'+new_username+'" is already taken.'
} else {
$scope.available = true;
$scope.message = 'Great! "'+new_username+'" is available!'
}
$scope.available = result.ok;
$scope.message = result.message;
$scope.checking = false;
});
});
Expand Down Expand Up @@ -68,7 +60,6 @@ <h3 class="blue-text">Attention: you can only change your username once. Make it
New username:
<input type="text" name="new_username"
ng-model="new_username"
ng-pattern="/\w*[a-zA-Z]\w*/"
ng-keypress="keypress($event)">
<a href ng-click="check()" class="fs-button blue medium">Available?</a>
<a href ng-show="available" class="fs-button green medium" ng-click="submit()">Change!</a>
Expand Down
3 changes: 3 additions & 0 deletions djangoproject/templates/core2/include/navbar.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
<ul id="menu1" class="dropdown-menu" aria-labelledby="drop_user">
<li><a href="{{ user.get_view_link }}">View Profile</a></li>
<li><a href="/user/edit">Edit Profile</a></li>
{% if user.getUserInfo.can_change_username %}
<li><a href="/user/change_username">Change username</a></li>
{% endif %}
{% if user.has_usable_password %}
<li><a href="/accounts/password/change">Change password</a></li>
{% endif %}
Expand Down
73 changes: 66 additions & 7 deletions djangoproject/templates/core2/useredit.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,50 @@
{% extends "core2/base_old.html" %}

{% block head %}
<script src="/static/js/angular.min.js"></script>
<script src="/static/js/fsapi.js"></script>
<script src="/static/js/fsutil.js"></script>
<script>
angular.module('main', ['fsapi']).config(
function($interpolateProvider, $httpProvider){
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}
).controller('ChangeUsernameCtrl', function ChangeUsernameCtrl($scope, FSApi){
$scope.curr_username = '{{ user.username }}';
$scope.username = $scope.curr_username;

$scope.keypress = function(evt){
if(evt.charCode == 13){
$scope.check();
evt.preventDefault();
}
return false;
};

$scope.check = function(evt){
$scope.checking = true;
var username = $scope.username;
FSApi.check_username_availability(username).onResult(function(result){
$scope.$apply(function(){
$scope.available = result.ok;
$scope.message = result.message;
$scope.checking = false;
});
});
evt.preventDefault();
}

$scope.submit = function(){
$('#le_form').submit();
}
});

</script>
{% endblock head %}


{% block mainContent%}
<h3>{{user.first_name}} {{user.last_name}} - edit profile</h3>
<hr>
Expand Down Expand Up @@ -50,7 +96,7 @@ <h3>You're about to terminate your account. Are you sure?</h3>
</form>
</div>

<div class="row-fluid">
<div class="row-fluid" ng-app="main" ng-controller="ChangeUsernameCtrl">
<div class="span2">
<img src="{{user.gravatar_url_big}}"/>
<a href="http://en.gravatar.com/" target="_gravatar">Change picture</a> <i class="icon-question-sign icon-white popopo" rel="popover" data-content="We display your picture as it is registered in Gravatar. Go ahead and create your account there if you still don't have one" data-original-title="No upload here!"></i>
Expand All @@ -62,12 +108,25 @@ <h3>You're about to terminate your account. Are you sure?</h3>

<input type="hidden" name="next" value="{{next}}">

<div class="control-group">
<label class="control-label" for="screenName">Screen name</label>
<div class="controls">
<input type="text" class="span4" id="screenName" name="screenName" value="{{userinfo.screenName}}">
</div>
</div>
{% if can_edit_username %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls" style="display: inline; margin-left: 20px;">
<input type="text" class="span4" style="display: inline" id="username" name="username" ng-model="username" ng-keypress="keypress($event)">
<button ng-click="check($event)" style="display: inline" ng-show="username != curr_username">Check availability</button>
<p class="help-block" style="margin-left: 160px;">
<img src="/static/img2/ajax-loader.gif" ng-show="checking">
<span ng-class="{success:available, fail:!available}">{[{ message }]}</span>
</p>
</div>
</div>
{% else %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls" style="padding-top: 6px">{{ user.username }}</div>
</div>
{% endif %}

<div class="control-group">
<label class="control-label" for="primaryEmail">Primary email
{% if user.email and not userinfo.is_primary_email_verified %}
Expand Down

0 comments on commit 5f4cce0

Please sign in to comment.