Commit f9325045 authored by buttle's avatar buttle

Fixed Site delete and Installation create.

Added __str__ to models
parent 2b11576f
......@@ -19,142 +19,17 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
from GNGforms import db
from GNGforms import persistence
import pprint
from pprint import pprint as pp
def migrateMongoSchema(schemaVersion):
if schemaVersion < 2:
# changes in schema version 2
# replace "expireDate" for "expiryConditions"
for form in db.forms.find():
if 'expireDate' in form:
expireDate=form['expireDate']
form["expiryConditions"] = {"expireDate": expireDate}
db.forms.save(form)
db.forms.update_one({"_id": form["_id"]}, {"$unset": {'expireDate' :1}})
else:
break
# get rid of from ObjectIDs
for form in db.forms.find():
if not isinstance(form['author'], str):
form['author']=str(form['author'])
db.forms.save(form)
else:
break
schemaVersion=2
if schemaVersion < 3:
# changes in schema version 2
# change the editor's list to a dict and include notification preferences
for form in db.forms.find():
if isinstance(form['editors'], list):
newEditorsDict={}
for editor in form['editors']:
newEditorsDict[editor]={'notification': form['notification']}
form['editors']=newEditorsDict
db.forms.update_one({"_id": form["_id"]}, {"$unset": {'notification' :1}, "$set": {"editors": form['editors']}})
else:
break
schemaVersion=3
if schemaVersion < 4:
# this originally didn't work
# get rid of from ObjectIDs
for form in db.forms.find():
form['author']=str(form['author'])
db.forms.save(form)
# this originally didn't work
for form in db.forms.find():
newEditorsDict={}
for editor in form['editors']:
newEditorsDict[editor]={'notification': form['notification']}
if not newEditorsDict:
newEditorsDict[form['author']]={'notification': {'newEntry': False}}
form['editors']=newEditorsDict
db.forms.update_one({"_id": form["_id"]}, {"$unset": {'notification' :1}, "$set": {"editors": form['editors']}})
schemaVersion=4
if schemaVersion < 5:
for site in db.sites.find():
site["siteName"]="GNGforms"
db.sites.save(site)
schemaVersion=5
if schemaVersion < 6:
# Add field conditions
for form in db.forms.find():
form["expiryConditions"]["fields"]={}
conditions=form["expiryConditions"]
db.forms.update_one({"_id": form["_id"]}, {"$set": {"expiryConditions": conditions}})
schemaVersion=6
if schemaVersion < 7:
# Add log array
for form in db.forms.find():
db.forms.update_one({"_id": form["_id"]}, {"$set": {"log": []}})
schemaVersion=7
if schemaVersion < 8:
# Add expired bool
forms=[persistence.Form(_id=form['_id']) for form in db.forms.find()]
for form in forms:
for editor in form.data['editors']:
form.data['editors'][editor]["notification"]["expiredForm"]=True
form.update({ "expired": form.hasExpired(),
"editors": form.data['editors']
})
schemaVersion=8
if schemaVersion < 9:
# Add site footnote. To be displayed at foot of forms.
for site in db.sites.find():
db.sites.update_one({"_id": site["_id"]}, {"$set": {"defaultFormFootNote": {
'markdown': "",
'html': "",
'enabled': False }} })
for form in db.forms.find():
db.forms.update_one({"_id": form["_id"]}, {"$set": {"showFootNote": False }})
schemaVersion=9
if schemaVersion < 10:
# Changed site footnote to personalDataConsent.
for site in db.sites.find():
consent=site["defaultFormFootNote"]
db.sites.update_one({"_id": site["_id"]}, {"$unset": {'defaultFormFootNote' :1}, "$set": {"personalDataConsent": consent} })
for form in db.forms.find():
boolean=form["showFootNote"]
db.forms.update_one({"_id": form["_id"]}, {"$unset": {'showFootNote' :1}, "$set": {"requireDataConsent": boolean }})
schemaVersion=10
if schemaVersion < 11:
# Added smtp config per Site.
for site in db.sites.find():
smtpConfig={
"host": "smtp.%s" % site["hostname"],
"port": 25,
"encryption": "",
"user": "",
"password": "",
"noreplyAddress": site["noreplyEmailAddress"]
}
db.sites.update_one({"_id": site["_id"]}, {"$unset": {'noreplyEmailAddress' :1},"$set": {"smtpConfig": smtpConfig} })
"""
Mirgations previous to schemaVersion 14 used the pymongo library.
schemaVersion >= 14 uses mongoengine.
"""
schemaVersion=11
def migrateMongoSchema(schemaVersion):
#if schemaVersion == 13:
# ....
# schemaVersion = 14
if schemaVersion < 12:
# Add restrictedAccess
for form in db.forms.find():
db.forms.update_one({"_id": form["_id"]}, {"$set": {"restrictedAccess": False}})
schemaVersion=12
if schemaVersion == 12:
# Add admin prefs. to forms
for form in db.forms.find():
db.forms.update_one({"_id": form["_id"]}, {"$set": {"adminPreferences": { "public": True }}})
schemaVersion=13
# this can't be a good migration setup :(
return schemaVersion
......@@ -20,21 +20,29 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
from GNGforms import app, db
from GNGforms.utils import *
from GNGforms.migrate import migrateMongoSchema
from bson.objectid import ObjectId
from flask import flash, request, g
from flask_babel import gettext
from urllib.parse import urlparse
import os, string, random, datetime, json, markdown
from mongoengine import QuerySet
from pprint import pformat
from pprint import pprint as pp
#from pprint import pprint as pp
def get_obj_values_as_dict(obj):
values = {}
fields = type(obj).__dict__['_fields']
for key, _ in fields.items():
value = getattr(obj, key, None)
values[key] = value
return values
class HostnameQuerySet(QuerySet):
def ensure_hostname(self, **kwargs):
if not g.isRootUser and not 'hostname' in kwargs:
kwargs={'hostname':g.site.hostname, **kwargs}
print("ensure_hostname kwargs: %s" % kwargs)
#print("ensure_hostname kwargs: %s" % kwargs)
return self.filter(**kwargs)
......@@ -59,7 +67,6 @@ def isNewUserRequestValid(form):
return True
class User(db.Document):
meta = {'collection': 'users', 'queryset_class': HostnameQuerySet}
username = db.StringField(required=True)
......@@ -76,13 +83,8 @@ class User(db.Document):
def __init__(self, *args, **kwargs):
db.Document.__init__(self, *args, **kwargs)
def get_obj_values_as_dict(self):
values = {}
fields = type(self).__dict__['_fields']
for key, _ in fields.items():
value = getattr(self, key, None)
values[key] = value
return values
def __str__(self):
return pformat({'User': get_obj_values_as_dict(self)})
@classmethod
def create(cls, newUserData):
......@@ -116,7 +118,7 @@ class User(db.Document):
for rootUser in rootUsers:
if not rootUser['email'] in emails:
emails.append(rootUser['email'])
print("new form notify %s" % emails)
#print("new form notify %s" % emails)
return emails
@classmethod
......@@ -134,7 +136,7 @@ class User(db.Document):
for rootUser in rootUsers:
if not rootUser['email'] in emails:
emails.append(rootUser['email'])
print("new user notify: %s" % emails)
#print("new user notify: %s" % emails)
return emails
@classmethod
......@@ -186,10 +188,7 @@ class User(db.Document):
def toggleBlocked(self):
if self.isRootUser():
self.blocked=False
elif self.blocked:
self.blocked=False
else:
self.blocked=True
self.blocked=False if self.blocked else True
self.save()
return self.blocked
......@@ -258,13 +257,8 @@ class Form(db.Document):
db.Document.__init__(self, *args, **kwargs)
self.site=Site.objects(hostname=self.hostname).first()
def get_obj_values_as_dict(self):
values = {}
fields = type(self).__dict__['_fields']
for key, _ in fields.items():
value = getattr(self, key, None)
values[key] = value
return values
def __str__(self):
return pformat({'Form': get_obj_values_as_dict(self)})
@classmethod
def find(cls, **kwargs):
......@@ -312,8 +306,8 @@ class Form(db.Document):
def totalEntries(self):
return len(self.entries)
def is_enabled(self):
if not self.adminPreferences['public']:
def isEnabled(self):
if not (self.user.enabled and self.adminPreferences['public']):
return False
return self.enabled
......@@ -400,8 +394,10 @@ class Form(db.Document):
new_form.save()
return new_form
"""
def update(self, data):
db.forms.update_one({'_id': self.form['_id']}, {"$set": data})
"""
def deleteEntries(self):
self.entries=[]
......@@ -416,7 +412,7 @@ class Form(db.Document):
def getEditors(self):
editors=[]
for editor_id in self.editors:
print (editor_id)
#print (editor_id)
user=User.find(id=editor_id)
if user:
editors.append(user)
......@@ -454,11 +450,10 @@ class Form(db.Document):
return total
def isPublic(self):
if self.expired or self.adminPreferences['public']==False:
return False
if not (self.enabled and self.user.enabled):
if not self.isEnabled() or self.expired:
return False
return True
else:
return True
def isShared(self):
if self.areEntriesShared():
......@@ -546,18 +541,9 @@ class Site(db.Document):
def __init__(self, *args, **kwargs):
db.Document.__init__(self, *args, **kwargs)
print("site.hostname: %s" % self.hostname)
def __repr__(self):
print("<Site=%s" % self.hostname)
def get_obj_values_as_dict(self):
values = {}
fields = type(self).__dict__['_fields']
for key, _ in fields.items():
value = getattr(self, key, None)
values[key] = value
return values
def __str__(self):
return pformat({'Site': get_obj_values_as_dict(self)})
@classmethod
def create(cls):
......@@ -593,7 +579,6 @@ class Site(db.Document):
@classmethod
def find(cls, *args, **kwargs):
print("site_newsite: %s" % kwargs)
site = cls.findAll(*args, **kwargs).first()
if not site:
site=Site.create()
......@@ -668,11 +653,11 @@ class Site(db.Document):
self.save()
return self.scheme
def delete(self):
user=User.findAll(hostname=self.hostname)
def deleteSite(self):
users=User.findAll(hostname=self.hostname)
for user in users:
user.deleteUser()
invites = Invite.findAll(hostname=self.site['hostname'])
invites = Invite.findAll(hostname=self.hostname)
for invite in invites:
invite.delete()
return self.delete()
......@@ -689,13 +674,8 @@ class Invite(db.Document):
def __init__(self, *args, **kwargs):
db.Document.__init__(self, *args, **kwargs)
def get_obj_values_as_dict(self):
values = {}
fields = type(self).__dict__['_fields']
for key, _ in fields.items():
value = getattr(self, key, None)
values[key] = value
return values
def __str__(self):
return pformat({'Invite': get_obj_values_as_dict(self)})
@classmethod
def create(cls, hostname, email, message, admin=False):
......@@ -728,12 +708,15 @@ class Invite(db.Document):
class Installation(db.Document):
name = db.StringField(required=True)
schemaVersion = db.StringField(required=True)
schemaVersion = db.IntField(required=True)
created = db.StringField(required=True)
def __init__(self, *args, **kwargs):
db.Document.__init__(self, *args, **kwargs)
def __str__(self):
return pformat({'Installation': get_obj_values_as_dict(self)})
@classmethod
def get(cls):
installation=cls.objects.first()
......@@ -761,8 +744,6 @@ class Installation(db.Document):
if migratedUpTo:
self.schemaVersion=migratedUpTo
self.save()
#db.installation.save(self.installation)
#db.installation.update_one({"_id": self.installation["_id"]}, {"$set": {'schemaVersion': migratedUpTo}})
return self.schemaVersion
else:
return None
......
......@@ -30,58 +30,12 @@ from GNGforms.utils import *
from GNGforms.email import *
from form_templates import formTemplates
from pprint import pprint as pp
def make_url_for(function, **kwargs):
kwargs["_external"]=True
kwargs["_scheme"]=g.site.scheme
return url_for(function, **kwargs)
@app.route('/test', methods=['GET'])
def test():
sites=Site.findAll()
"""
for site in sites:
#print(site.id)
pp (site.get_obj_values_as_dict())
# print (site.get_obj_values_as_dict())
"""
"""
users=User.objects
for user in users:
if user.username=='alice':
print (user.get_obj_values_as_dict())
user.
user.save()
"""
form=Form.find()
pp (form.get_obj_values_as_dict())
"""
for form in forms:
#pp (form.get_obj_values_as_dict())
#form.expiryConditions={"expireDate": None, "fields": {}}
#form.save()
print("form: '%s' %s %s" % (form.slug, form.id, form.hostname))
"""
"""
invites=Invite.objects
for invite in invites:
pp (invite.get_obj_values_as_dict())
"""
#form=Form.find(id='5e638385174b6f10dd39bf46')
#pp (form.get_obj_values_as_dict())
#form.enabled=True
#pp(form.structure[0])
#form.save()
return render_template('test.html', sites=sites)
@app.before_request
def before_request():
g.current_user=None
......@@ -247,7 +201,7 @@ def inspect_form(id):
flash(gettext("No form found"), 'warning')
return redirect(make_url_for('my_forms'))
pp(queriedForm.get_obj_values_as_dict())
print(queriedForm)
if not g.current_user.canInspectForm(queriedForm):
flash(gettext("Permission needed to view form"), 'warning')
......@@ -414,14 +368,10 @@ def set_field_condition(id):
@app.route('/forms/edit/<string:id>', methods=['GET', 'POST'])
@enabled_user_required
def edit_form(id=None):
#pp = pprint.PrettyPrinter(indent=4)
ensureSessionFormKeys()
session['form_id']=None
queriedForm=None
if id:
print("id form-edit: %s" % id)
queriedForm = Form.find(id=id)
if queriedForm:
if not queriedForm.isEditor(g.current_user):
......@@ -452,7 +402,7 @@ def edit_form(id=None):
""" formbuilder may return empty label attributes or label attributes with html. """
if 'label' in formElement:
# formbuilder adds a trailing '<br>' to lables.
#formElement['label']=formElement['label'].rstrip('<br>')
# formElement['label']=formElement['label'].rstrip('<br>')
if not stripHTMLTagsForLabel(formElement['label']):
# we need some text (any text) to save as a label.
formElement['label'] = "Label"
......@@ -461,13 +411,10 @@ def edit_form(id=None):
session['formStructure'] = json.dumps(formStructure)
session['afterSubmitTextMD'] = escapeMarkdown(request.form['afterSubmitTextMD'])
return redirect(make_url_for('preview_form'))
return render_template('edit-form.html', host_url=g.site.host_url)
@app.route('/forms/check-slug-availability/<string:slug>', methods=['POST'])
@enabled_user_required
def is_slug_available(slug):
......@@ -953,7 +900,6 @@ def new_user(token=None):
""" Login / Logout """
@app.route('/site/login', methods=['POST'])
......@@ -964,10 +910,11 @@ def login():
if user and verifyPassword(request.form['password'], user.password):
session["user_id"]=str(user.id)
if not user.validatedEmail:
return redirect(make_url_for('user_settings', username=username))
return redirect(make_url_for('user_settings', username=user.username))
else:
return redirect(make_url_for('my_forms'))
session["user_id"]=None
if "user_id" in session:
session.pop("user_id")
flash(gettext("Bad credentials"), 'warning')
return redirect(make_url_for('index'))
......@@ -1225,7 +1172,7 @@ def delete_site(hostname):
flash(gettext("Cannot delete current site"), 'warning')
return redirect(make_url_for('user_settings', username=g.current_user.username))
queriedSite.delete()
queriedSite.deleteSite()
flash(gettext("Deleted %s" % (queriedSite.host_url)), 'success')
return redirect(make_url_for('user_settings', username=g.current_user.username))
else:
......@@ -1431,3 +1378,8 @@ def JsonResponse(json_response="1", status_code=200):
response.headers.add('content-length', len(json_response))
response.status_code=status_code
return response
@enabled_user_required
@app.route('/test', methods=['GET'])
def test():
return render_template('test.html', sites=[])
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment