def _createObjects(self): '''Method to populate the database with some initial objects.''' # Site: reuse default site 'example.com' site = Site.objects.get(pk=1) logging.info("Updating site: %s" % site) site.name = self.siteManager.get('SITE_NAME') site.domain = self.siteManager.get('SITE_DOMAIN') site.save() # Test project #if not Project.objects.filter(short_name=DEFAULT_PROJECT_SHORT_NAME).exists(): if Project.objects.count() == 0: logging.info("Creating project: %s" % DEFAULT_PROJECT_SHORT_NAME) project = Project.objects.create(short_name=DEFAULT_PROJECT_SHORT_NAME, long_name='Test Project', description='This is a test project', site=site, active=True) initProject(project) project.save() # create Administrator user - one time only if User.objects.count() == 0: # create User object logging.info("Creating admin user") user = User(first_name='Admin', last_name='User', username=ROOTADMIN_USERNAME, email=self.siteManager.get('EMAIL_SENDER', section=SECTION_EMAIL), is_staff=True, is_superuser=True) if settings.ESGF_CONFIG: password = self._getRootAdminPassword() else: password = DEFAULT_ROOTADMIN_PASSWORD user.set_password(password) user.save() # create UserProfile object userp = UserProfile(user=user, institution='Institution', city='City', state='State', country='Country', site=site, last_password_update=datetime.datetime.now()) userp.clearTextPassword=password # needed by esgfDatabaseManager, NOT saved as clear text in any database userp.save() # ESGF database setup if settings.ESGF_CONFIG: # create rootAdmin openid: https://<ESGF_HOSTNAME>/esgf-idp/openid/rootAdmin openid = esgfDatabaseManager.buildOpenid(ROOTADMIN_USERNAME) UserOpenID.objects.create(user=user, claimed_id=openid, display_id=openid) logging.info("Created openid:%s for CoG administrator: %s" % (openid, user.username) ) # insert rootAdmin user in ESGF database logging.info("Inserting CoG administrator: %s in ESGF database" % user.username) esgfDatabaseManager.insertEsgfUser(user.profile) # must create and enable 'esgf.idp.peer" as federated CoG peer if settings.IDP_REDIRECT is not None and settings.IDP_REDIRECT.strip() != '': idpHostname = settings.IDP_REDIRECT.lower().replace('http://','').replace('https://','') try: idpPeerSite = PeerSite.objects.get(site__domain=idpHostname) idpPeerSite.enabled=True idpPeerSite.save() except ObjectDoesNotExist: site = Site.objects.create(name=idpHostname, domain=idpHostname) idpPeerSite = PeerSite.objects.create(site=site, enabled=True) print '\tCreated IdP Peer site: %s with enabled=%s' % (idpPeerSite, idpPeerSite.enabled)
def ac_subscribe(request, group_name): """ View to request an access control permission. Currently, it can only be used to request ROLE_USER. """ title = "%s Data Access Request" % group_name template = "cog/access_control/subscribe.html" # prevent requests to 'wheel' group if group_name == "wheel": return HttpResponseForbidden(PERMISSION_DENIED_MESSAGE) # check that group exists in local database group_list = registrationService.listGroups() group_names = [str(groupDict["name"]) for groupDict in group_list] if not group_name in group_names: return HttpResponseForbidden(GROUP_NOT_FOUND_MESSAGE) # display submission form if request.method == "GET": try: status = registrationService.status(request.user.profile.openid(), group_name, ROLE_USER) except ObjectDoesNotExist: # user does not exist in ESGF database print "Inserting user into ESGF security database" esgfDatabaseManager.insertEsgfUser(request.user.profile) status = None licenseTxt = None licenseHtml = None try: licenseFile = "cog/access_control/licenses/%s.txt" % group_name licenseTxt = render_to_string(licenseFile) except TemplateDoesNotExist: try: licenseFile = "cog/access_control/licenses/%s.html" % group_name licenseHtml = render_to_string(licenseFile) except TemplateDoesNotExist: pass return render( request, template, { "title": title, "group_name": group_name, "status": status, "licenseTxt": licenseTxt, "licenseHtml": licenseHtml, }, ) # process submission form else: approved = registrationService.subscribe(request.user.profile.openid(), group_name, ROLE_USER) # notify node administrators if not approved: notifyAdmins(group_name, request.user.id, request) # (GET-POST-REDIRECT) return HttpResponseRedirect( reverse("ac_subscribe", kwargs={"group_name": group_name}) + "?approved=%s" % approved )
def ac_subscribe(request, group_name): """ View to request an access control permission. Currently, it can only be used to request ROLE_USER. """ title = '%s Data Access Request' % group_name template = 'cog/access_control/subscribe.html' # prevent requests to 'wheel' group if group_name == 'wheel': return HttpResponseForbidden(PERMISSION_DENIED_MESSAGE) # check that group exists in local database group_list = registrationService.listGroups() group_names = [str(groupDict['name']) for groupDict in group_list] if not group_name in group_names: return HttpResponseForbidden(GROUP_NOT_FOUND_MESSAGE) # display submission form if request.method == 'GET': try: status = registrationService.status(request.user.profile.openid(), group_name, ROLE_USER) except ObjectDoesNotExist: # user does not exist in ESGF database print 'Inserting user into ESGF security database' esgfDatabaseManager.insertEsgfUser(request.user.profile) status = None licenseTxt = None licenseHtml = None try: licenseFile = 'cog/access_control/licenses/%s.txt' % group_name licenseTxt = render_to_string(licenseFile) except TemplateDoesNotExist: try: licenseFile = 'cog/access_control/licenses/%s.html' % group_name licenseHtml = render_to_string(licenseFile) except TemplateDoesNotExist: pass return render( request, template, { 'title': title, 'group_name': group_name, 'status': status, 'licenseTxt': licenseTxt, 'licenseHtml': licenseHtml }) # process submission form else: approved = registrationService.subscribe(request.user.profile.openid(), group_name, ROLE_USER) # notify node administrators if not approved: notifyAdmins(group_name, request.user.id, request) # (GET-POST-REDIRECT) return HttpResponseRedirect( reverse('ac_subscribe', kwargs={'group_name': group_name}) + "?approved=%s" % approved)
def _createObjects(self): '''Method to populate the database with some initial objects.''' # Site: reuse default site 'example.com' site = Site.objects.get(pk=1) logging.info("Updating site: %s" % site) site.name = self.siteManager.get('SITE_NAME') site.domain = self.siteManager.get('SITE_DOMAIN') site.save() # Test project #if not Project.objects.filter(short_name=DEFAULT_PROJECT_SHORT_NAME).exists(): if Project.objects.count() == 0: logging.info("Creating project: %s" % DEFAULT_PROJECT_SHORT_NAME) project = Project.objects.create( short_name=DEFAULT_PROJECT_SHORT_NAME, long_name='Test Project', description='This is a test project', site=site, active=True) initProject(project) project.save() # create Administrator user - one time only if User.objects.count() == 0: # create User object logging.info("Creating admin user") user = User(first_name='Admin', last_name='User', username=ROOTADMIN_USERNAME, email=self.siteManager.get('EMAIL_SENDER', section=SECTION_EMAIL), is_staff=True, is_superuser=True) if settings.ESGF_CONFIG: password = self._getRootAdminPassword() else: password = DEFAULT_ROOTADMIN_PWD user.set_password(password) user.save() # create UserProfile object userp = UserProfile(user=user, institution='Institution', city='City', state='State', country='Country', site=site, last_password_update=datetime.datetime.now()) userp.clearTextPwd = password # needed by esgfDatabaseManager, NOT saved as clear text in any database userp.save() # ESGF database setup if settings.ESGF_CONFIG: # create rootAdmin openid: https://<ESGF_HOSTNAME>/esgf-idp/openid/rootAdmin openid = esgfDatabaseManager.buildOpenid(ROOTADMIN_USERNAME) UserOpenID.objects.create(user=user, claimed_id=openid, display_id=openid) logging.info("Created openid:%s for CoG administrator: %s" % (openid, user.username)) # insert rootAdmin user in ESGF database logging.info( "Inserting CoG administrator: %s in ESGF database" % user.username) esgfDatabaseManager.insertEsgfUser(user.profile) esgfRegistrationServiceImpl.subscribe(openid, ROOTADMIN_GROUP, ROOTADMIN_ROLE) esgfRegistrationServiceImpl.process(openid, ROOTADMIN_GROUP, ROOTADMIN_ROLE, True) # must create and enable 'esgf.idp.peer" as federated CoG peer if settings.IDP_REDIRECT is not None and settings.IDP_REDIRECT.strip( ) != '': idpHostname = settings.IDP_REDIRECT.lower().replace( 'http://', '').replace('https://', '') try: idpPeerSite = PeerSite.objects.get(site__domain=idpHostname) idpPeerSite.enabled = True idpPeerSite.save() except ObjectDoesNotExist: site = Site.objects.create(name=idpHostname, domain=idpHostname) idpPeerSite = PeerSite.objects.create(site=site, enabled=True) print '\tCreated IdP Peer site: %s with enabled=%s' % ( idpPeerSite, idpPeerSite.enabled)
def user_add(request): # redirection URL _next = request.GET.get('next', None) or request.POST.get('next', None) # redirect to another node if necessary if redirectToIdp(): redirect_url = settings.IDP_REDIRECT + request.path if _next is not None: redirect_url += ("?next=%s" % urllib.quote_plus(_next)) print 'Redirecting account creation to: %s' % redirect_url return HttpResponseRedirect(redirect_url) # create URLs formset UserUrlFormsetFactory = modelformset_factory(UserUrl, form=UserUrlForm, exclude=('profile',), can_delete=True, extra=2) if request.method == 'GET': form = UserForm(initial={'next': _next}) # initialize form with redirect URL formset = UserUrlFormsetFactory(queryset=UserUrl.objects.none(), prefix='url') # empty formset return render_user_form(request, form, formset, title='Create User Profile') else: # form with bounded data form = UserForm(request.POST, request.FILES,) # formset with bounded data formset = UserUrlFormsetFactory(request.POST, queryset=UserUrl.objects.none(), prefix='url') if form.is_valid() and formset.is_valid(): # create a user from the form but don't save it to the database yet because the password is not encoded yet user = form.save(commit=False) # must reset the password through the special method that encodes it correctly clearTextPwd = form.cleaned_data['password'] user.set_password(clearTextPwd) # save user to database user.save() print 'Created user=%s' % user.username # create openid if settings.ESGF_CONFIG: openid = form.cleaned_data['openid'] print 'Creating openid=%s' % openid userOpenID = UserOpenID.objects.create(user=user, claimed_id=openid, display_id=openid) print 'Added openid=%s for user=%s into COG database' % (openid, user.username) # use additional form fields to create user profile userp = UserProfile(user=user, institution=form.cleaned_data['institution'], city=form.cleaned_data['city'], state=form.cleaned_data['state'], country=form.cleaned_data['country'], department=form.cleaned_data['department'], researchKeywords=form.cleaned_data['researchKeywords'], researchInterests=form.cleaned_data['researchInterests'], subscribed=form.cleaned_data['subscribed'], private=form.cleaned_data['private'], image=form.cleaned_data['image'], last_password_update=datetime.datetime.now()) # save user profile --> will trigger userProfile post_save userp.save() # NOTE: this field is NOT persisted in the CoG database but it is used by insertEsgfUser() below userp.clearTextPwd = clearTextPwd # insert into ESGF database if settings.ESGF_CONFIG: esgfDatabaseManager.insertEsgfUser(userp) # create user data cart datacart = DataCart(user=user) datacart.save() # must assign URL to this user urls = formset.save(commit=False) for url in urls: url.profile = userp url.save() # generate thumbnail image if userp.image is not None: try: generateThumbnail(userp.image.path, THUMBNAIL_SIZE_SMALL) except ValueError: pass # image does not exist, ignore # notify user, node administrators of new registration notifyUserOfRegistration(user) notifyAdminsOfUserRegistration(user,request) # subscribe to mailing list ? if userp.subscribed: subscribeUserToMailingList(user, request) # redirect to login page with special message login_url = reverse('login')+"?message=user_add" if _next is not None and len(_next.strip()) > 0: login_url += ("&next=%s" % urllib.quote_plus(_next)) # redirect to absolute URL (possibly at an another node) if 'http' in _next: url = urlparse(_next) login_url = '%s://%s%s' % (url.scheme, url.netloc, login_url) # append openid to initial login_url if userp.openid() is not None: login_url += "&openid=%s" % urllib.quote_plus(userp.openid()) login_url += "&username=%s" % urllib.quote_plus(userp.user.username) response = HttpResponseRedirect(login_url) # set openid cookie on this host set_openid_cookie(response, userp.openid()) print 'New user account created: redirecting to login url: %s' % login_url return response else: if not form.is_valid(): print "Form is invalid: %s" % form.errors elif not formset.is_valid(): print "URL formset is invalid: %s" % formset.errors return render_user_form(request, form, formset, title='Create User Profile')