def join(id_usergroup, id_user=None, status=None): """Join group.""" group = Usergroup.query.get_or_404(id_usergroup) id_user2join = id_user or current_user.get_id() user2join = User.query.get_or_404(id_user2join) form = UserJoinGroupForm() user_status = None if form.user_status and form.user_status.data: user_status = UserUsergroup.USER_STATUS['ADMIN'] try: group.join(user2join, status=user_status) except AccountSecurityError: flash(_( 'You have not enough right to ' 'add user "%(x_nickname)s" to the group "%(x_groupname)s"', x_nickname=user2join.nickname, x_groupname=group.name), "error") return redirect(url_for('.index')) except SQLAlchemyError: flash(_('User "%(x_nickname)s" can\'t join the group "%(x_groupname)s"', x_nickname=user2join.nickname, x_groupname=group.name), "error") if id_user: return redirect(url_for('.members', id_usergroup=id_usergroup)) else: return redirect(url_for('.index')) current_user.reload() flash(_('%(user)s join the group "%(name)s".', user='******'+user2join.nickname+'"' if id_user else "You", name=group.name), 'success') redirect_url = form.redirect_url.data or url_for('.index') return redirect(redirect_url)
def remove_current_user_from_group(self, usergroup_name): from invenio.modules.accounts.models import User, Usergroup from flask.ext.login import current_user user = User.query.get(current_user.get_id()) ug = Usergroup.query.filter(Usergroup.name == usergroup_name).one() ug.leave(user) current_user.reload()
def create_and_login_user(self, user_nickname=None, user_password=None): """Create test user and log him in.""" from invenio.modules.accounts.models import User self.user_nickname = user_nickname or "tester" self.user_password = user_password or "tester" # remove the user if he exists self.user = User.query.filter( User.nickname == self.user_nickname).first() if self.user: try: db.session.delete(self.user) db.session.commit() except: db.session.rollback() raise # create the user email = "{}@b2share.com".format(self.user_nickname) self.user = User(email=email, nickname=self.user_nickname) self.user.password = self.user_password try: db.session.add(self.user) db.session.commit() except: db.session.rollback() raise from invenio.ext.login import login_user from flask.ext.login import current_user login_user(self.user.id) current_user.reload() self.assertEqual(current_user.get_id(), self.user.id) self.safe_login_web_user(self.user_nickname, self.user_password) return self.user.id
def is_record_editable(recid): if current_user.is_super_admin: return True if current_user.is_guest: return False (domain, owner_email, is_private, admin_can_edit_published_record) = _get_record_info(recid) # if private record, allow owner of the record if is_private and current_user['email'] == owner_email: return True # the user's groups are not updated unless we call reload() current_user.reload() if get_domain_admin_group(domain) in current_user.get('group', []): # if the current user is community admin if is_private: # allow community admin to edit private records return True if admin_can_edit_published_record: # some domains allow community admin to edit public records return True return False
def add_current_user_to_group(self, usergroup_name): from invenio.modules.accounts.models import User, Usergroup, UserUsergroup from flask.ext.login import current_user user = User.query.get(current_user.get_id()) ug = Usergroup.query.filter(Usergroup.name == usergroup_name).one() ug.join(user, status=UserUsergroup.USER_STATUS['MEMBER']) current_user.reload()
def addLit(): # isUpdate = False form = AddLitForm() if form.validate_on_submit(): ######################################################### # What should be here instead is an icontains statement showing the user similar entries # It should then allow the user to select if they would like to update or not, # and then update or add based on that ######################################################### lit = Lit.objects(title__iexact = form.title.data, author__iexact = form.author.data).first() if lit is not None: flash("This is already in the DB. This is the page") ## Change addLit to updateLit. return render_template('lit.html', lit = lit) editHist = LitEditRecord(lastUserEdited = current_user.name) lit = Lit(refType = form.refType.data, title = form.title.data, author = form.author.data, primaryField = form.primaryField.data, creator = current_user.name) lit.save() lit.update(set__yrPublished = form.yrPublished.data) lit.update(set__sourceTitle = form.sourceTitle.data) lit.update(set__editor = form.editor.data) lit.update(set__placePublished = form.placePublished.data) lit.update(set__publisher = form.publisher.data) lit.update(set__volume = form.volume.data) lit.update(set__number = form.number.data) lit.update(set__pages = form.pages.data) lit.update(set__abstract = form.abstract.data) lit.update(set__notes = form.notes.data) lit.update(set__secondaryField = form.secondaryField.data) if form.link.data is not None: print "this is the link: " + form.link.data lit.update(set__link = form.link.data) # Add keywords keywordslist = (form.keywords.data).split(",") print "this is the keywords: " + form.keywords.data for x in range(0, len(keywordslist)): key = str(keywordslist[x].strip()) print key print type(key) lit.update(push__keywords = key) # Update lit history lit.update(push__l_edit_record=editHist) lit.update(set__last_edit = editHist) lit.reload() # Update user edit history userHist = UserEditRecord(litEdited = str(lit.id), operation = "add", litEditedTitle = lit.title) current_user.update(push__u_edit_record = userHist) current_user.reload() flash("Successfully added!") return redirect(url_for('main.lit', lit_id = lit.id)) return render_template('addLit.html', form = form)
def addLit(): # Create new add lit form form = AddLitForm() # On form submission if form.validate_on_submit(): # If the literature is already in the database, then do not add the material, return lit = Lit.objects(title__iexact = form.title.data, author__iexact = form.author.data, pages__iexact = form.pages.data).first() if lit is not None: flash("This is already in the DB. This is the page") return render_template('lit.html', lit = lit) # Create a new lit object, save to db first, then update fields lit = Lit(refType = form.refType.data, title = form.title.data, author = form.author.data, primaryField = form.primaryField.data, creator = current_user.name) lit.save() lit.update(set__yrPublished = form.yrPublished.data) lit.update(set__sourceTitle = form.sourceTitle.data) lit.update(set__editor = form.editor.data) lit.update(set__placePublished = form.placePublished.data) lit.update(set__publisher = form.publisher.data) lit.update(set__volume = form.volume.data) lit.update(set__number = form.number.data) lit.update(set__pages = form.pages.data) lit.update(set__abstract = form.abstract.data) lit.update(set__notes = form.notes.data) lit.update(set__secondaryField = form.secondaryField.data) # Add user's edit in edit history editHist = LitEditRecord(lastUserEdited = current_user.name) # If the link field is not empty, save the link too # If statement is done because update fails when attempting to save an empty string if form.link.data is not None: lit.update(set__link = form.link.data) # Add keywords into the db as a listField keywordslist = (form.keywords.data).split(",") for x in range(0, len(keywordslist)): key = str(keywordslist[x].strip()) lit.update(push__keywords = key) # Update lit history lit.update(push__l_edit_record=editHist) lit.update(set__last_edit = editHist) lit.reload() # Update user edit history userHist = UserEditRecord(litEdited = str(lit.id), operation = "add", litEditedTitle = lit.title) current_user.update(push__u_edit_record = userHist) current_user.reload() flash("Successfully added!") return redirect(url_for('main.lit', lit_id = lit.id)) return render_template('addLit.html', form = form)
def deleteLiterature(lit_id): lit = Lit.objects( id__exact = lit_id).first() if lit is None: flash("No literature like this in the database.") else: userHist = UserEditRecord(litEdited = str(lit_id), litEditedTitle = lit.title, operation = "delete") current_user.update(push__u_edit_record=userHist) current_user.reload() lit.delete() flash("Literature has been deleted!") return redirect(url_for('main.search'))
def join(id_usergroup, status=None): """Join group.""" group = Usergroup.query.get(id_usergroup) if group is None: return abort(400) group.join() db.session.merge(group) db.session.commit() current_user.reload() flash(_('You join a group %(name)s.', name=group.name), 'success') return redirect(url_for('.index'))
def updateLitSub(lit_id): form = AddLitForm() lit = Lit.objects(id__iexact=lit_id).first() # Update all the fields of the object ( Could possibly be done in a simpler fashion ) if form.validate_on_submit(): lit.update(set__title=form.title.data) lit.update(set__refType=form.refType.data) lit.update(set__author=form.author.data) lit.update(set__primaryField=form.primaryField.data) lit.update(set__yrPublished=form.yrPublished.data) lit.update(set__sourceTitle=form.sourceTitle.data) lit.update(set__editor=form.editor.data) lit.update(set__placePublished=form.placePublished.data) lit.update(set__publisher=form.publisher.data) lit.update(set__volume=form.volume.data) lit.update(set__number=form.number.data) lit.update(set__pages=form.pages.data) lit.update(set__abstract=form.abstract.data) lit.update(set__notes=form.notes.data) lit.update(set__secondaryField=form.secondaryField.data) lit.update(set__link=form.link.data) # Clear the objects keywords lit.update(set__keywords=[]) # Separate the keywords field string by comma keywordslist = (form.keywords.data).split(",") # Push each key into the obj list field for x in range(0, len(keywordslist)): key = str(keywordslist[x].strip()) if key is not None: lit.update(push__keywords=key) # Add new Lit history obj editHist = LitEditRecord(lastUserEdited=current_user.name) lit.update(push__l_edit_record=editHist) lit.update(set__last_edit=editHist) lit.reload() # Add new User edit history obj userHist = UserEditRecord(litEdited=str(lit.id), operation="update", litEditedTitle=lit.title) current_user.update(push__u_edit_record=userHist) current_user.reload() lit = Lit.objects(id__iexact=lit_id).first() flash(lit.title + " has been updated") else: flash(lit.title + " failed to be updated") return render_template('lit.html', lit=lit)
def index(): """List all user groups.""" uid = current_user.get_id() current_user.reload() mg = UserUsergroup.query.join(UserUsergroup.usergroup).filter( UserUsergroup.id_user == uid).all() member_groups = dict(map(lambda ug: (ug.usergroup.name, ug), mg)) return render_template( 'groups/index.html', member_groups=member_groups, form=JoinUsergroupForm(), )
def deleteLiterature(lit_id): lit = Lit.objects(id__exact=lit_id).first() if lit is None: flash("No literature like this in the database.") else: userHist = UserEditRecord(litEdited=str(lit_id), litEditedTitle=lit.title, operation="delete") current_user.update(push__u_edit_record=userHist) current_user.reload() lit.delete() flash("Literature has been deleted!") return redirect(url_for('search.search'))
def delete(id_usergroup): """Delete a group.""" group = Usergroup.query.get_or_404(id_usergroup) id_user = current_user.get_id() if group.is_admin(id_user): db.session.delete(group) db.session.commit() current_user.reload() else: flash(_('Sorry, but you are not an admin of the group "%(name)s".', name=group.name), "error") return redirect(url_for(".index"))
def updateLitSub(lit_id): form = AddLitForm() lit = Lit.objects(id__iexact = lit_id).first() # Update all the fields of the object ( Could possibly be done in a simpler fashion ) if form.validate_on_submit(): lit.update(set__title=form.title.data) lit.update(set__refType=form.refType.data) lit.update(set__author=form.author.data) lit.update(set__primaryField=form.primaryField.data) lit.update(set__yrPublished = form.yrPublished.data) lit.update(set__sourceTitle = form.sourceTitle.data) lit.update(set__editor = form.editor.data) lit.update(set__placePublished = form.placePublished.data) lit.update(set__publisher = form.publisher.data) lit.update(set__volume = form.volume.data) lit.update(set__number = form.number.data) lit.update(set__pages = form.pages.data) lit.update(set__abstract = form.abstract.data) lit.update(set__notes = form.notes.data) lit.update(set__secondaryField= form.secondaryField.data) lit.update(set__link = form.link.data) # Clear the objects keywords lit.update(set__keywords = []) # Separate the keywords field string by comma keywordslist = (form.keywords.data).split(",") # Push each key into the obj list field for x in range(0, len(keywordslist)): key = str(keywordslist[x].strip()) if key is not None : lit.update(push__keywords = key) # Add new Lit history obj editHist = LitEditRecord(lastUserEdited = current_user.name) lit.update(push__l_edit_record=editHist) lit.update(set__last_edit = editHist) lit.reload() # Add new User edit history obj userHist = UserEditRecord(litEdited = str(lit.id), operation = "update", litEditedTitle = lit.title) current_user.update(push__u_edit_record=userHist) current_user.reload() lit = Lit.objects(id__iexact = lit_id).first() flash(lit.title + " has been updated") else: flash(lit.title + " failed to be updated") return render_template('lit.html', lit = lit)
def leave(id_usergroup): """Leave user group. :param id_usergroup: Identifier of user group. """ group = Usergroup.query.get(id_usergroup) if group is None: return abort(400) group.leave() db.session.merge(group) db.session.commit() current_user.reload() flash(_('You left a group %(name)s.', name=group.name), 'success') return redirect(url_for('.index'))
def manage(id_usergroup): """Manage user group.""" ug = Usergroup.query.filter_by(id=id_usergroup).one() form = UsergroupForm(request.form, obj=ug) if form.validate_on_submit(): if not ug.is_admin(current_user.get_id()): # not enough right to modify group flash(_('Sorry, you don\'t have enough right to be able ' 'to manage the group "%(name)s"', name=ug.name), 'error') return redirect(url_for(".index")) # get form data ug2form = Usergroup() form.populate_obj(ug2form) # update group oldname = ug.name ug.name = ug2form.name ug.description = ug2form.description ug.join_policy = ug2form.join_policy ug.login_method = ug2form.login_method # update in db try: db.session.merge(ug) db.session.commit() except IntegrityError: db.session.rollback() flash(_('Group properies error'), 'error') # reload form with old values return render_template( "groups/new.html", form=form, action=_('Update'), subtitle=oldname, ) except SQLAlchemyError: db.session.rollback() raise current_user.reload() return redirect(url_for(".index")) return render_template( "groups/new.html", form=form, action=_('Update'), subtitle=ug.name, )
def new(): """Create new user group.""" form = UsergroupForm(request.form) if form.validate_on_submit(): ug = Usergroup() form.populate_obj(ug) ug.join(status=UserUsergroup.USER_STATUS['ADMIN']) db.session.add(ug) db.session.commit() current_user.reload() return redirect(url_for(".index")) return render_template( "groups/new.html", form=form, )
def index(): """List all user groups.""" uid = current_user.get_id() current_user.reload() form = JoinUsergroupForm() form.id_usergroup.set_remote( url_for('webgroup.search_groups', id_user=uid) + "?query=%QUERY") user = User.query.get(uid) uugs = dict(map(lambda uug: (uug.usergroup.name, uug), user.usergroups)) return render_template( 'groups/index.html', uugs=uugs, form=form, )
def updateLitSub(lit_id): form = AddLitForm() lit = Lit.objects(id__iexact = lit_id).first() if form.validate_on_submit(): lit.update(set__title=form.title.data) lit.update(set__refType=form.refType.data) lit.update(set__author=form.author.data) lit.update(set__primaryField=form.primaryField.data) lit.update(set__yrPublished = form.yrPublished.data) lit.update(set__sourceTitle = form.sourceTitle.data) lit.update(set__editor = form.editor.data) lit.update(set__placePublished = form.placePublished.data) lit.update(set__publisher = form.publisher.data) lit.update(set__volume = form.volume.data) lit.update(set__number = form.number.data) lit.update(set__pages = form.pages.data) lit.update(set__abstract = form.abstract.data) lit.update(set__notes = form.notes.data) lit.update(set__secondaryField= form.secondaryField.data) lit.update(set__link = form.link.data) lit.update(set__keywords = []) keywordslist = (form.keywords.data).split(",") print "this is the keywords: " + form.keywords.data for x in range(0, len(keywordslist)): key = str(keywordslist[x].strip()) if key is not None : lit.update(push__keywords = key) # Update Lit history editHist = LitEditRecord(lastUserEdited = current_user.name) lit.update(push__l_edit_record=editHist) lit.update(set__last_edit = editHist) lit.reload() # Update User edit history userHist = UserEditRecord(litEdited = str(lit.id), operation = "update", litEditedTitle = lit.title) current_user.update(push__u_edit_record=userHist) current_user.reload() lit = Lit.objects(id__iexact = lit_id).first() flash(lit.title + " has been updated") else: flash(lit.title + " failed to be updated") return render_template('lit.html', lit = lit)
def is_record_editable(recid): if current_user.is_super_admin: return True if current_user.is_guest: return False (domain, owner_email, is_private) = _get_record_info(recid) # if private record, allow owner of the record if is_private and current_user['email'] == owner_email: return True # if private record, allow community admin # the user's groups are not updated unless we call reload() current_user.reload() if is_private and get_domain_admin_group(domain) in current_user.get('group', []): return True return False
def new(): """Create new user group.""" form = UsergroupForm(request.form) if form.validate_on_submit(): ug = Usergroup() id_user = current_user.get_id() user2join = User.query.get_or_404(id_user) form.populate_obj(ug) ug.join(status=UserUsergroup.USER_STATUS['ADMIN'], user=user2join) db.session.add(ug) try: db.session.commit() except IntegrityError: # catch integrity error db.session.rollback() flash(_('Group properies error'), 'error') # reload form with old values return render_template( "groups/new.html", form=form, action=_('Create'), subtitle=_("New group"), ) except: # catch unknown error db.session.rollback() raise # group finally created current_user.reload() flash(_('Group "%(name)s" successfully created', name=ug.name), 'success') return redirect(url_for(".index")) return render_template( "groups/new.html", form=form, action=_('Create'), subtitle=_("New group"), )
def leave(id_usergroup, id_user=None): """Leave user group. :param id_usergroup: Identifier of user group. """ group = Usergroup.query.get_or_404(id_usergroup) id_user2remove = id_user or current_user.get_id() user2remove = User.query.get_or_404(id_user2remove) try: group.leave(user2remove) except AccountSecurityError: flash(_( 'You have not enough right to ' 'remove user "%(x_nickname)s" from group "%(x_groupname)s"', x_nickname=user2remove.nickname, x_groupname=group.name), "error") return redirect(url_for('.index')) except IntegrityUsergroupError: flash(_( 'Sorry, user "%(x_nickname)s" can leave the group ' '"%(x_groupname)s" without admins, please delete the ' 'group if you want to leave.', x_nickname=user2remove.nickname, x_groupname=group.name), "error") return redirect(url_for('.index')) try: db.session.merge(group) db.session.commit() except SQLAlchemyError: db.session.rollback() raise current_user.reload() flash(_('%(user)s left the group "%(name)s".', user='******'+user2remove.nickname+'"' if id_user else "You", name=group.name), 'success') if id_user and id_user != current_user.get_id(): return redirect(url_for('.members', id_usergroup=id_usergroup)) else: return redirect(url_for('.index'))
def account_setup(remote, token, resp): """Perform additional setup after user have been logged in.""" from invenio.modules.oauthclient.utils import oauth_link_external_id from invenio.ext.sqlalchemy import db # Retrieve ORCID from response. orcid = resp.get("orcid") # Set ORCID in extra_data. token.remote_account.extra_data = {"orcid": orcid} user = token.remote_account.user # Create user <-> external id link. oauth_link_external_id(user, dict(id=orcid, method="orcid")) # Fill user full name if not already set if user and not any([user.given_names, user.family_name]): # Query ORCID to get the real name response = remote.get("{0}/orcid-bio".format(orcid), headers={'Accept': 'application/orcid+json'}, content_type="application/json") if response.status == 200: try: name = response.data["orcid-profile"]["orcid-bio"][ "personal-details"] user.given_names = name["given-names"]["value"] user.family_name = name["family-name"]["value"] except KeyError: current_app.logger.exception( "Unexpected return format from ORCID: {0}".format( repr(response.data))) return db.session.add(user) # Refresh user cache current_user.reload()
def add_staff(**member_data): member = get_or_404(User, **member_data) current_user.add_staff(member) current_user.reload()
def addLit(): # Create new add lit form form = AddLitForm() # On form submission if form.validate_on_submit(): # If the literature is already in the database, then do not add the material, return lit = Lit.objects(title__iexact=form.title.data, author__iexact=form.author.data, pages__iexact=form.pages.data).first() if lit is not None: flash("This is already in the DB. This is the page") return render_template('lit.html', lit=lit) # Create a new lit object, save to db first, then update fields lit = Lit(refType=form.refType.data, title=form.title.data, author=form.author.data, primaryField=form.primaryField.data, creator=current_user.name) lit.save() lit.update(set__yrPublished=form.yrPublished.data) lit.update(set__sourceTitle=form.sourceTitle.data) lit.update(set__editor=form.editor.data) lit.update(set__placePublished=form.placePublished.data) lit.update(set__publisher=form.publisher.data) lit.update(set__volume=form.volume.data) lit.update(set__number=form.number.data) lit.update(set__pages=form.pages.data) lit.update(set__abstract=form.abstract.data) lit.update(set__notes=form.notes.data) lit.update(set__secondaryField=form.secondaryField.data) # Add user's edit in edit history editHist = LitEditRecord(lastUserEdited=current_user.name) # If the link field is not empty, save the link too # If statement is done because update fails when attempting to save an empty string if form.link.data is not None: lit.update(set__link=form.link.data) # Add keywords into the db as a listField keywordslist = (form.keywords.data).split(",") for x in range(0, len(keywordslist)): key = str(keywordslist[x].strip()) lit.update(push__keywords=key) # Update lit history lit.update(push__l_edit_record=editHist) lit.update(set__last_edit=editHist) lit.reload() # Update user edit history userHist = UserEditRecord(litEdited=str(lit.id), operation="add", litEditedTitle=lit.title) current_user.update(push__u_edit_record=userHist) current_user.reload() flash("Successfully added!") return redirect(url_for('main.lit', lit_id=lit.id)) return render_template('addLit.html', form=form)