def access(): """Access.""" try: email = EmailConfirmationSerializer().load_token( request.values['mailcookie'])['data']['email'] u = User.query.filter(User.email == email).one() u.note = 1 try: db.session.commit() except SQLAlchemyError: db.session.rollback() flash(_('Authorization failled.'), 'error') redirect('/') if current_user.is_authenticated(): current_user.reload() flash(_('Your email address has been validated'), 'success') else: UserInfo(u.id).reload() flash( _('Your email address has been validated, and you can ' 'now proceed to sign-in.'), 'success') except Exception: current_app.logger.exception("Authorization failed.") flash(_('The authorization token is invalid.'), 'error') return redirect('/')
def oauth_register(account_info, form_data=None): """Register user if possible.""" from invenio_accounts.models import User email = account_info.get("email") if form_data and form_data.get("email"): email = form_data.get("email") if email: note = '1' if cfg['CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT']: note = '2' if not User.query.filter_by(email=email).first(): # Email does not already exists. so we can proceed to register # user. u = User(nickname=account_info.get('nickname', ''), email=email, password=None, note=note) try: db.session.add(u) db.session.commit() except Exception: current_app.logger.exception("Cannot create user") return None # verify the email if note == '2': u.verify_email() return UserInfo(u.id) return None
def test_change_password_password(self): """Test ChangePasswordForm password.""" from invenio_accounts.forms import ChangePasswordForm from flask_login import login_user, logout_user from invenio_ext.login import UserInfo not_valid_pwd = "x" * (self.min_len - 1) valid_pwd = "x" * self.min_len login_user(UserInfo(self.user.id)) form = ChangePasswordForm(current_password=self.password, password=valid_pwd, password2=valid_pwd) assert form.validate() is True form = ChangePasswordForm(current_password=self.password, password=not_valid_pwd, password2=not_valid_pwd) assert form.validate() is False form = ChangePasswordForm(current_password=self.password, password=valid_pwd, password2=valid_pwd + 'different') assert form.validate() is False logout_user()
def test_profile_form_nickname(self): """Test ProfileForm nickname.""" from invenio_accounts.forms import ProfileForm from flask_login import login_user, logout_user from invenio_ext.login import UserInfo form = ProfileForm(nickname=self.nickname, email=self.email, repeat_email=self.email) assert form.validate() is False form = ProfileForm(nickname=" nickname", email=self.email, repeat_email=self.email) assert form.validate() is False form = ProfileForm(nickname="nickname ", email=self.email, repeat_email=self.email) assert form.validate() is False form = ProfileForm(nickname="nick.name", email=self.email, repeat_email=self.email) assert form.validate() is False form = ProfileForm(nickname="nick@name", email=self.email, repeat_email=self.email) assert form.validate() is False form = ProfileForm(nickname="*****@*****.**", email=self.email, repeat_email=self.email) assert form.validate() is False form = ProfileForm(nickname="guest", email=self.email, repeat_email=self.email) assert form.validate() is False form = ProfileForm(nickname="Guest", email=self.email, repeat_email=self.email) assert form.validate() is False login_user(UserInfo(self.user.id)) form = ProfileForm(nickname=self.nickname, email=self.email, repeat_email=self.email) assert form.validate() is True self.delete_objects([self.user]) form = ProfileForm(nickname=self.nickname, email=self.email, repeat_email=self.email) assert form.validate() is True logout_user()
def setUp(self): """setting up helper variables for tests""" from invenio_ext.login import UserInfo self.user_info = { 'email': '*****@*****.**', 'uid': 1000, 'group': ['patata', 'cetriolo'], 'remote_ip': '127.0.0.1', 'guest': '0' } self.guest = UserInfo(None)
def oauth_get_user(client_id, account_info=None, access_token=None): """Retrieve user object for the given request. Uses either the access token or extracted account information to retrieve the user object. """ if access_token: token = RemoteToken.get_by_token(client_id, access_token) if token: return UserInfo(token.remote_account.user_id) if account_info: external_id = _get_external_id(account_info) if external_id: u = UserEXT.query.filter_by(id=external_id['id'], method=external_id['method']).first() if u: return UserInfo(u.id_user) if account_info.get('email'): u = User.query.filter_by(email=account_info['email']).first() if u: return UserInfo(u.id) return None
def setUp(self): """Setup.""" try: self.clear('simple') except Exception: pass from invenio_ext.login import UserInfo from invenio_deposit import field_widgets from invenio_deposit import fields from invenio_deposit.form import WebDepositForm from invenio_deposit.types import SimpleRecordDeposition class SimpleRecordTestForm(WebDepositForm): keywords = fields.DynamicFieldList( fields.StringField( widget_classes='form-control', widget=field_widgets.ColumnInput(class_="col-xs-10"), ), label='Keywords', add_label='Add another keyword', icon='fa fa-tags fa-fw', widget_classes='', min_entries=1, ) publication_date = fields.Date( label=_('Publication date'), icon='fa fa-calendar fa-fw', description='Required. Format: YYYY-MM-DD.', default=date.today(), validators=[], widget=field_widgets.date_widget, widget_classes='input-sm', export_key='imprint.date', ) class simple(SimpleRecordDeposition): name = "Simple Test" name_plural = "Simple Tests" group = "Tests" draft_definitions = { 'default': SimpleRecordTestForm, } @classmethod def process_sip_metadata(cls, deposition, metadata): self.assert_process_metadata(deposition, metadata) self.register(simple) UserInfo(1, force=True)
def acc_authorize_action(req, name_action, authorized_if_no_roles=False, batch_args=False, **arguments): """ Given the request object (or the user_info dictionary, or the uid), checks if the user is allowed to run name_action with the given parameters. If authorized_if_no_roles is True and no role exists (different than superadmin) that are authorized to execute the given action, the authorization will be granted. Returns (0, msg) when the authorization is granted, (1, msg) when it's not. """ from invenio_ext.login import UserInfo from werkzeug.local import LocalProxy if isinstance(req, LocalProxy): req = req._get_current_object() if isinstance(req, UserInfo): user_info = req uid = user_info.get_id() elif type(req) is dict: uid = req.get('uid', None) user_info = req elif type(req) not in [int, long]: uid = current_user.get_id() user_info = UserInfo(uid) # FIXME else: user_info = current_user roles_list = acc_find_possible_roles(name_action, always_add_superadmin=True, batch_args=batch_args, **arguments) if not batch_args: roles_list = [roles_list] result = [] for roles in roles_list: if acc_is_user_in_any_role(user_info, roles): # User belong to at least one authorized role # or User is SUPERADMIN ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0]) elif len(roles) <= 1: ## No role is authorized for the given action/arguments if authorized_if_no_roles: # User is authorized because no authorization exists for the # given action/arguments ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0]) else: # User is not authorized. ret_val = (20, CFG_WEBACCESS_WARNING_MSGS[20] % cgi.escape(name_action)) else: # User is not authorized in_a_web_request_p = bool(user_info.get('uri', '')) ret_val = ( 1, "%s %s" % (CFG_WEBACCESS_WARNING_MSGS[1], (in_a_web_request_p and "%s %s" % (CFG_WEBACCESS_MSGS[0] % quote(user_info.get('uri', '')), CFG_WEBACCESS_MSGS[1]) or ""))) result.append(ret_val) # FIXME removed CERN specific hack! return result if batch_args else result[0]
def acc_authorize_action(req, name_action, authorized_if_no_roles=False, batch_args=False, **arguments): """ Given the request object (or the user_info dictionary, or the uid), checks if the user is allowed to run name_action with the given parameters. If authorized_if_no_roles is True and no role exists (different than superadmin) that are authorized to execute the given action, the authorization will be granted. Returns (0, msg) when the authorization is granted, (1, msg) when it's not. """ from invenio_ext.login import UserInfo from werkzeug.local import LocalProxy if isinstance(req, LocalProxy): req = req._get_current_object() if isinstance(req, UserInfo): user_info = req uid = user_info.get_id() elif type(req) is dict: uid = req.get('uid', None) user_info = req elif type(req) not in [int, long]: uid = current_user.get_id() user_info = UserInfo(uid) # FIXME else: user_info = current_user roles_list = acc_find_possible_roles(name_action, always_add_superadmin=True, batch_args=batch_args, **arguments) if not batch_args: roles_list = [roles_list] result = [] for roles in roles_list: if acc_is_user_in_any_role(user_info, roles): # User belong to at least one authorized role # or User is SUPERADMIN ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0]) elif len(roles) <= 1: ## No role is authorized for the given action/arguments if authorized_if_no_roles: # User is authorized because no authorization exists for the # given action/arguments ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0]) else: # User is not authorized. ret_val = ( 20, CFG_WEBACCESS_WARNING_MSGS[20] % cgi.escape(name_action) ) else: # User is not authorized in_a_web_request_p = bool(user_info.get('uri', '')) ret_val = (1, "%s %s" % ( CFG_WEBACCESS_WARNING_MSGS[1], (in_a_web_request_p and "%s %s" % ( CFG_WEBACCESS_MSGS[0] % quote(user_info.get('uri', '')), CFG_WEBACCESS_MSGS[1]) or ""))) result.append(ret_val) # FIXME removed CERN specific hack! return result if batch_args else result[0]