Skip to content

Commit

Permalink
[Backport fixes from master]
Browse files Browse the repository at this point in the history
  • Loading branch information
afabiani committed Jun 6, 2018
1 parent e54eb92 commit af53713
Show file tree
Hide file tree
Showing 18 changed files with 267 additions and 118 deletions.
96 changes: 88 additions & 8 deletions geonode/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@

from guardian.models import Group

from allauth.account.utils import user_field, user_email, user_username

from ..utils import json_response


def verify_access_token(key):
try:
Expand All @@ -54,6 +58,65 @@ def get_client_ip(request):
return ip


def extract_headers(request):
"""
Extracts headers from the Django request object
:param request: The current django.http.HttpRequest object
:return: a dictionary with OAuthLib needed headers
"""
headers = request.META.copy()
if "wsgi.input" in headers:
del headers["wsgi.input"]
if "wsgi.errors" in headers:
del headers["wsgi.errors"]
if "HTTP_AUTHORIZATION" in headers:
headers["Authorization"] = headers["HTTP_AUTHORIZATION"]

return headers


@csrf_exempt
def user_info(request):
headers = extract_headers(request)
user = request.user

if not user:
out = {'success': False,
'status': 'error',
'errors': {'user': ['User is not authenticated']}
}
return json_response(out, status=401)

if 'Authorization' not in headers and 'Bearer' not in headers["Authorization"]:
out = {'success': False,
'status': 'error',
'errors': {'auth': ['No token provided.']}
}
return json_response(out, status=403)

groups = [group.name for group in user.groups.all()]
if user.is_superuser:
groups.append("admin")

user_info = json.dumps({
"sub": str(user.id),
"name": " ".join([user_field(user, 'first_name'), user_field(user, 'last_name')]),
"given_name": user_field(user, 'first_name'),
"family_name": user_field(user, 'last_name'),
"email": user_email(user),
"preferred_username": user_username(user),
"groups": groups
})

response = HttpResponse(
user_info,
content_type="application/json"
)
response['Cache-Control'] = 'no-store'
response['Pragma'] = 'no-cache'
return response


@csrf_exempt
def verify_token(request):
"""
Expand All @@ -74,9 +137,11 @@ def verify_token(request):
)
"""

if (request.POST and request.POST['token']):
if (request.POST and 'token' in request.POST):
token = None
try:
token = verify_access_token(request.POST['token'])
access_token = request.POST.get('token')
token = verify_access_token(access_token)
except Exception as e:
return HttpResponse(
json.dumps({
Expand All @@ -86,18 +151,33 @@ def verify_token(request):
content_type="application/json"
)

return HttpResponse(
json.dumps({
if token:
token_info = json.dumps({
'client_id': token.application.client_id,
'issued_to': token.user.username,
'user_id': token.user.id,
'username': token.user.username,
'issued_to': token.user.username,
'access_token': access_token,
'email': token.user.email,
'verified_email': 'true',
'access_type': 'online',
'expires_in': (token.expires - timezone.now()).total_seconds() * 1000
}),
content_type="application/json"
)
})

response = HttpResponse(
token_info,
content_type="application/json"
)
response["Authorization"] = ("Bearer %s" % access_token)
return response
else:
return HttpResponse(
json.dumps({
'error': 'No access_token from server.'
}),
status=403,
content_type="application/json"
)

return HttpResponse(
json.dumps({
Expand Down
5 changes: 5 additions & 0 deletions geonode/base/management/commands/updategeoip.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,11 @@ def handle(self, *args, **options):
self.handle_old_format(open('output.bin', 'r'), fname)
else:
self.handle_new_format(open('output.bin', 'r'), fname)
try:
# Cleaning up
os.remove('output.bin')
except OSError:
pass


def handle_new_format(self, f, fname):
Expand Down
14 changes: 8 additions & 6 deletions geonode/layers/templates/layers/layer_style_manage.html
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,16 @@ <h4>{% trans "Available styles" %}</h4>
{{ block.super }}
<script type="text/javascript">
$(function () {

$('#style-select').multiSelect({
afterSelect: function(values){
$('#default_style').append($("<option/>", {
value: values[0],
text: values[0]
}));
$("#style-select :selected").each(function() {
if(this.value === values[0]) {
$('#default_style').append($("<option/>", {
value: this.value,
text: this.text
}));
}
});
},
afterDeselect: function(values){
$('#default_style option').each(function() {
Expand All @@ -84,7 +87,6 @@ <h4>{% trans "Available styles" %}</h4>
});
}
});

});
</script>
{% endblock %}
4 changes: 2 additions & 2 deletions geonode/layers/templates/upload/layer_upload_time.html
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ <h4 class="modal-title">Modal Header</h4>
function iso8601DateFormatter(value, row, index) {
var time_checked_value = String(value);
if(data_validation && !time_checked_value.match(
/(^\d{4}$)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d)|(\d{4}-[01]\d-[0-3]\d)|(\d{4}\/[01]\d\/[0-3]\d)/
/(^\d{4}$)|(\d{4}-[01]\d)|(\d{4}-[01]\d-[0-3]\d)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\dZ+)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\dZ)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\dZ)/
)) {
time_checked_value = '<font color="red" title="' + value +'{% trans " does NOT match any valid ISO-8601 Date-Time string!" %}">' +
'<i class="fa fa-exclamation-triangle" aria-hidden="true"></i>&nbsp;' + value +'</font>';
Expand All @@ -349,7 +349,7 @@ <h4 class="modal-title">Modal Header</h4>
function iso8601Formatter(value, row, index) {
var time_checked_value = String(value);
if(data_validation && !time_checked_value.match(
/(^\d{4}$)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\dZ+)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\dZ)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\dZ)/
/(^\d{4}$)|(\d{4}-[01]\d)|(\d{4}-[01]\d-[0-3]\d)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\dZ+)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\dZ)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\dZ)/
)) {
time_checked_value = '<font color="red" title="' + value +'{% trans " does NOT match any valid ISO-8601 Date-Time string!" %}">' +
'<i class="fa fa-exclamation-triangle" aria-hidden="true"></i>&nbsp;' + value +'</font>';
Expand Down
1 change: 1 addition & 0 deletions geonode/people/adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ def render_mail(self, template_prefix, email, context):
slug__in=user.groupmember_set.filter().values_list("group__slug", flat=True))
enhanced_context = context.copy()
enhanced_context.update({
"username": user.username,
"inviter_name": full_name or str(user),
"inviter_first_name": user.first_name or str(user),
"inviter_id": user.id,
Expand Down
44 changes: 42 additions & 2 deletions geonode/people/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,29 @@
#
#########################################################################

from uuid import uuid4

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.contrib.auth.models import AbstractUser, UserManager
from django.contrib.sites.models import Site
from django.db.models import signals
from django.conf import settings

from taggit.managers import TaggableManager

from geonode.base.enumerations import COUNTRIES
from geonode.groups.models import GroupProfile
from geonode.notifications_helper import send_notification
# from geonode.notifications_helper import send_notification

from allauth.account.signals import user_signed_up
from allauth.socialaccount.signals import social_account_added
# from account.models import EmailAddress

from .utils import format_address
from .signals import (update_user_email_addresses,
notify_admins_new_signup)
from .languages import LANGUAGES
from .timezones import TIMEZONES

Expand Down Expand Up @@ -174,7 +182,28 @@ def _notify_account_activated(self):
"""Notify user that its account has been activated by a staff member"""
became_active = self.is_active and not self._previous_active_state
if became_active and self.last_login is None:
send_notification(users=(self,), label="account_active")
try:
# send_notification(users=(self,), label="account_active")

from invitations.adapters import get_invitations_adapter
current_site = Site.objects.get_current()
ctx = {
'username': self.username,
'current_site': current_site,
'site_name': current_site.name,
'email': self.email,
'inviter': self,
}

email_template = 'pinax/notifications/account_active/account_active'

get_invitations_adapter().send_mail(
email_template,
self.email,
ctx)
except BaseException:
import traceback
traceback.print_exc()


def get_anonymous_user_instance(Profile):
Expand All @@ -194,4 +223,15 @@ def profile_post_save(instance, sender, **kwargs):
return


""" Connect relevant signals to their corresponding handlers. """
social_account_added.connect(
update_user_email_addresses,
dispatch_uid=str(uuid4()),
weak=False
)
user_signed_up.connect(
notify_admins_new_signup,
dispatch_uid=str(uuid4()),
weak=False
)
signals.post_save.connect(profile_post_save, sender=Profile)
21 changes: 2 additions & 19 deletions geonode/people/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,10 @@

import logging

from uuid import uuid4

from allauth.account.signals import user_signed_up
from allauth.socialaccount.signals import social_account_added

from allauth.account.models import EmailAddress
from django.contrib.auth import get_user_model
from django.db import IntegrityError
from django.db.models import Q

from geonode.notifications_helper import send_notification

Expand All @@ -57,22 +53,9 @@ def update_user_email_addresses(sender, **kwargs):


def notify_admins_new_signup(sender, **kwargs):
staff = get_user_model().objects.filter(is_staff=True)
staff = get_user_model().objects.filter(Q(is_active=True) & (Q(is_staff=True) | Q(is_superuser=True)))
send_notification(
users=staff,
label="account_approve",
extra_context={"from_user": kwargs["user"]}
)


""" Connect relevant signals to their corresponding handlers. """
social_account_added.connect(
update_user_email_addresses,
dispatch_uid=str(uuid4()),
weak=False
)
user_signed_up.connect(
notify_admins_new_signup,
dispatch_uid=str(uuid4()),
weak=False
)
1 change: 0 additions & 1 deletion geonode/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,6 @@

'CLIENT_ID_GENERATOR_CLASS': 'oauth2_provider.generators.ClientIdGenerator',
}

# authorized exempt urls needed for oauth when GeoNode is set to lockdown
AUTH_EXEMPT_URLS = ('/api/o/*', '/api/roles', '/api/adminRole', '/api/users',)

Expand Down
2 changes: 1 addition & 1 deletion geonode/static/geonode/js/upload/LayerInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ define(function (require, exports) {
$(this).text('Done').attr('disabled','disabled');
var id = (new Date()).getTime();
var newWin = window.open(window.location.href,
id, "toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=800,height=600,left = 240,top = 212");
id, "toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=1100,height=800,left = 240,top = 100");
common.make_request({
url: event.data.url,
async: true,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{% load i18n %}

{% trans "Your account has been approved and is now active." %} ({{ username }})

{% trans "You can use the login form at" %}: http://{{ current_site.name }}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{% load i18n %}{% trans "Welcome at" %} {{ current_site.name }}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{% load i18n %}

{% trans "Your account has been approved and is now active." %}:
{% trans "Your account has been approved and is now active." %}

{% trans "You can use the login form at" %}: http://{{ current_site }}
4 changes: 3 additions & 1 deletion geonode/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from . import views

from geonode.api.urls import api
from geonode.api.views import verify_token, roles, users, admin_role
from geonode.api.views import verify_token, user_info, roles, users, admin_role

from geonode import geoserver, qgis_server # noqa
from geonode.utils import check_ogc_backend
Expand Down Expand Up @@ -155,6 +155,8 @@
# Api Views
url(r'^api/o/v4/tokeninfo',
verify_token, name='tokeninfo'),
url(r'^api/o/v4/userinfo',
user_info, name='userinfo'),
url(r'^api/roles', roles, name='roles'),
url(r'^api/adminRole', admin_role, name='adminRole'),
url(r'^api/users', users, name='users'),
Expand Down

0 comments on commit af53713

Please sign in to comment.