Beispiel #1
0
def user_invite(context, data_dict):
    """Invite a new user.

    You must be authorized to create group members.

    :param email: the email of the user to be invited to the group
    :type email: string
    :param group_id: the id or name of the group
    :type group_id: string
    :param role: role of the user in the group. One of ``member``, ``editor``,
        or ``admin``
    :type role: string

    :returns: the newly created yser
    :rtype: dictionary
    """
    _check_access("user_invite", context, data_dict)

    schema = context.get("schema", ckan.logic.schema.default_user_invite_schema())
    data, errors = _validate(data_dict, schema, context)
    if errors:
        raise ValidationError(errors)

    name = _get_random_username_from_email(data["email"])
    password = str(random.SystemRandom().random())
    data["name"] = name
    data["password"] = password
    data["state"] = ckan.model.State.PENDING
    user_dict = _get_action("user_create")(context, data)
    user = ckan.model.User.get(user_dict["id"])
    member_dict = {"username": user.id, "id": data["group_id"], "role": data["role"]}
    _get_action("group_member_create")(context, member_dict)
    mailer.send_invite(user)
    return model_dictize.user_dictize(user, context)
    def account_requests_management(self):
        ''' Approve or reject an account request
        '''
        action = request.params['action']
        user_id = request.params['id']
        user_name = request.params['name']
        user = model.User.get(user_id)
        #user_email = logic.get_action('user_show')({},{'id': user_id})
        context1 = { 'user': model.Session.query(model.User).filter_by(sysadmin=True).first().name }
        org = logic.get_action('organization_list_for_user')({'user': user_name}, {'permission': 'read'})

        if org:
            user_delete = {
                'id': org[0]['name'],
                'object': user_name,
                'object_type': 'user'
            }

        context = {
            'model': model,
            'user': c.user,
            'session': model.Session,
        }
        activity_create_context = {
            'model': model,
            'user': user_name,
            'defer_commit': True,
            'ignore_auth': True,
            'session': model.Session
        }
        activity_dict = {
            'user_id': c.userobj.id,
            'object_id': user_id
        } 
        if action == 'forbid':
            object_id_validators['reject new user'] = user_id_exists
            activity_dict['activity_type'] = 'reject new user'
            logic.get_action('activity_create')(activity_create_context, activity_dict)
            # remove user, {{'user_email': user_email}}

            logic.get_action('user_delete')(context1, {'id':user_id})

            mailer.mail_recipient(user.name, user.email, 'Account request', 'Your account request has been denied.')

        elif action == 'approve':
            object_id_validators['approve new user'] = user_id_exists
            activity_dict['activity_type'] = 'approve new user'
            logic.get_action('activity_create')(activity_create_context, activity_dict)
            # Send invitation to complete registration
            try:
                mailer.send_invite(user)
            except Exception as e:
                log.error('Error emailing invite to user: %s', e)
                abort(500, _('Error: couldn''t email invite to user'))

        response.status = 200
        return render('admin/account_requests_management.html')
Beispiel #3
0
    def test_send_invite_email_with_group(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        group = factories.Group()
        role = 'member'

        # send email
        mailer.send_invite(user_obj, group_dict=group, role=role)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        msg = msgs[0]
        body = self.get_email_body(msg[3])
        assert_in(group['title'], body)
        assert_in(h.roles_translated()[role], body)
Beispiel #4
0
    def test_send_invite_email_with_org(self, mail_server):
        user = factories.User()
        user_obj = model.User.by_name(user["name"])

        org = factories.Organization()
        role = "admin"

        # send email
        mailer.send_invite(user_obj, group_dict=org, role=role)

        # check it went to the mock smtp server
        msgs = mail_server.get_smtp_messages()
        msg = msgs[0]
        body = self.get_email_body(msg[3])
        assert org["title"] in six.ensure_text(body)
        assert h.roles_translated()[role] in six.ensure_text(body)
Beispiel #5
0
    def test_send_invite_email_with_org(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        org = factories.Organization()
        role = 'admin'

        # send email
        mailer.send_invite(user_obj, group_dict=org, role=role)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        msg = msgs[0]
        body = self.get_email_body(msg[3])
        assert_in(org['title'], body)
        assert_in(h.roles_translated()[role], body)
Beispiel #6
0
    def test_send_invite_email_with_group(self, mail_server):
        user = factories.User()
        user_obj = model.User.by_name(user["name"])

        group = factories.Group()
        role = "member"

        # send email
        mailer.send_invite(user_obj, group_dict=group, role=role)

        # check it went to the mock smtp server
        msgs = mail_server.get_smtp_messages()
        msg = msgs[0]
        body = self.get_email_body(msg[3])
        assert group["title"] in six.ensure_text(body)
        assert h.roles_translated()[role] in six.ensure_text(body)
Beispiel #7
0
    def test_send_invite_email_with_org(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        org = factories.Organization()
        role = 'admin'

        # send email
        mailer.send_invite(user_obj, group_dict=org, role=role)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        msg = msgs[0]
        body = self.get_email_body(msg[3])
        assert_in(org['title'], body)
        assert_in(h.roles_translated()[role], body)
Beispiel #8
0
    def test_send_invite_email(self):
        user = model.User.by_name(u"bob")
        assert user.reset_key is None, user
        # send email
        mailer.send_invite(user)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        assert_equal(msg[1], config["smtp.mail_from"])
        assert_equal(msg[2], [model.User.by_name(u"bob").email])
        test_msg = mailer.get_invite_body(model.User.by_name(u"bob"))
        expected_body = self.mime_encode(test_msg, u"bob")
        assert expected_body in msg[3], "%r not in %r" % (expected_body, msg[3])
        assert user.reset_key is not None, user
Beispiel #9
0
    def test_send_invite_email_with_group(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        group = factories.Group()
        role = 'member'

        # send email
        mailer.send_invite(user_obj, group_dict=group, role=role)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        msg = msgs[0]
        body = self.get_email_body(msg[3])
        assert_in(group['title'], body)
        assert_in(h.roles_translated()[role], body)
    def test_send_invite_email(self):
        user = model.User.by_name(u'bob')
        assert user.reset_key is None, user
        # send email
        mailer.send_invite(user)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        assert_equal(msg[1], config['smtp.mail_from'])
        assert_equal(msg[2], [model.User.by_name(u'bob').email])
        test_msg = mailer.get_invite_body(model.User.by_name(u'bob'))
        expected_body = self.mime_encode(test_msg, u'bob')
        assert expected_body in msg[3], '%r not in %r' % (expected_body,
                                                          msg[3])
        assert user.reset_key is not None, user
Beispiel #11
0
    def test_send_invite_email_with_org(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        org = factories.Organization()
        role = 'admin'

        # We need to provide a context as url_for is used internally
        with self.app.flask_app.test_request_context():
            # send email
            mailer.send_invite(user_obj, group_dict=org, role=role)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        msg = msgs[0]
        body = self.get_email_body(msg[3])
        assert_in(org['title'], body)
        assert_in(h.roles_translated()[role], body)
Beispiel #12
0
    def test_send_invite_email(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])
        assert user_obj.reset_key is None, user_obj

        # send email
        mailer.send_invite(user_obj)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        assert_equal(msg[1], config['smtp.mail_from'])
        assert_equal(msg[2], [user['email']])
        test_msg = mailer.get_invite_body(user_obj)
        expected_body = self.mime_encode(test_msg, user['name'])

        assert_in(expected_body, msg[3])
        assert user_obj.reset_key is not None, user
Beispiel #13
0
    def test_invite_user_custom_subject(self):
        user = factories.User()
        user_obj = model.User.by_name(user["name"])

        mailer.send_invite(user_obj)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert len(msgs) == 1
        msg = msgs[0]
        extra_vars = {
            "site_title": config.get("ckan.site_title"),
        }
        expected = render_jinja2("emails/invite_user_subject.txt", extra_vars)
        expected = expected.split("\n")[0]

        subject = self.get_email_subject(msg[3])
        assert expected == subject
        assert "**test**" in subject
Beispiel #14
0
    def test_send_invite_email(self, mail_server):
        user = factories.User()
        user_obj = model.User.by_name(user["name"])
        assert user_obj.reset_key is None, user_obj

        # send email
        mailer.send_invite(user_obj)

        # check it went to the mock smtp server
        msgs = mail_server.get_smtp_messages()
        assert len(msgs) == 1
        msg = msgs[0]
        assert msg[1] == config["smtp.mail_from"]
        assert msg[2] == [user["email"]]
        test_msg = mailer.get_invite_body(user_obj)
        expected_body = self.mime_encode(test_msg + '\n', user["name"])

        assert expected_body in msg[3]
        assert user_obj.reset_key is not None, user
Beispiel #15
0
    def test_invite_user_custom_body(self):
        user = factories.User()
        user_obj = model.User.by_name(user["name"])

        mailer.send_invite(user_obj)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert len(msgs) == 1
        msg = msgs[0]
        extra_vars = {
            "reset_link": mailer.get_reset_link(user_obj),
            "user_name": user["name"],
            "site_title": config.get("ckan.site_title"),
        }
        expected = render_jinja2("emails/invite_user.txt", extra_vars)
        body = self.get_email_body(msg[3])
        assert expected == body
        assert "**test**" in body
Beispiel #16
0
    def test_invite_user_custom_body(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        mailer.send_invite(user_obj)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        extra_vars = {
            'reset_link': mailer.get_reset_link(user_obj),
            'user_name': user['name'],
            'site_title': config.get('ckan.site_title'),
        }
        expected = render_jinja2('emails/invite_user.txt', extra_vars)
        body = self.get_email_body(msg[3])
        assert_equal(expected, body)
        assert_in('**test**', body)
Beispiel #17
0
    def test_invite_user_custom_subject(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        mailer.send_invite(user_obj)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        extra_vars = {
            'site_title': config.get('ckan.site_title'),
        }
        expected = render_jinja2('emails/invite_user_subject.txt', extra_vars)
        expected = expected.split('\n')[0]

        subject = self.get_email_subject(msg[3])
        assert_equal(expected, subject)
        assert_in('**test**', subject)
Beispiel #18
0
    def test_invite_user_custom_body(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        mailer.send_invite(user_obj)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        extra_vars = {
            'reset_link': mailer.get_reset_link(user_obj),
            'user_name': user['name'],
            'site_title': config.get('ckan.site_title'),
        }
        expected = render_jinja2('emails/invite_user.txt',
                                 extra_vars)
        body = self.get_email_body(msg[3])
        assert_equal(expected, body)
        assert_in('**test**', body)
Beispiel #19
0
    def test_invite_user_custom_subject(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])

        mailer.send_invite(user_obj)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        extra_vars = {
            'site_title': config.get('ckan.site_title'),
        }
        expected = render_jinja2('emails/invite_user_subject.txt',
                                 extra_vars)
        expected = expected.split('\n')[0]

        subject = self.get_email_subject(msg[3])
        assert_equal(expected, subject)
        assert_in('**test**', subject)
Beispiel #20
0
    def test_send_invite_email(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])
        assert user_obj.reset_key is None, user_obj

        # send email
        mailer.send_invite(user_obj)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        assert_equal(msg[1], config['smtp.mail_from'])
        assert_equal(msg[2], [user['email']])
        test_msg = mailer.get_invite_body(user_obj)
        expected_body = self.mime_encode(test_msg,
                                         user['name'])

        assert_in(expected_body, msg[3])
        assert user_obj.reset_key is not None, user
Beispiel #21
0
def user_invite(context, data_dict):
    '''Invite a new user.

    You must be authorized to create group members.

    :param email: the email of the user to be invited to the group
    :type email: string
    :param group_id: the id or name of the group
    :type group_id: string
    :param role: role of the user in the group. One of ``member``, ``editor``,
        or ``admin``
    :type role: string

    :returns: the newly created yser
    :rtype: dictionary
    '''
    _check_access('user_invite', context, data_dict)

    schema = context.get('schema',
                         ckan.logic.schema.default_user_invite_schema())
    data, errors = _validate(data_dict, schema, context)
    if errors:
        raise ValidationError(errors)

    name = _get_random_username_from_email(data['email'])
    password = str(random.SystemRandom().random())
    data['name'] = name
    data['password'] = password
    data['state'] = ckan.model.State.PENDING
    user_dict = _get_action('user_create')(context, data)
    user = ckan.model.User.get(user_dict['id'])
    member_dict = {
        'username': user.id,
        'id': data['group_id'],
        'role': data['role']
    }
    _get_action('group_member_create')(context, member_dict)
    mailer.send_invite(user)
    return model_dictize.user_dictize(user, context)
Beispiel #22
0
def user_invite(context, data_dict):
    '''Invite a new user.

    You must be authorized to create group members.

    :param email: the email of the user to be invited to the group
    :type email: string
    :param group_id: the id or name of the group
    :type group_id: string
    :param role: role of the user in the group. One of ``member``, ``editor``,
        or ``admin``
    :type role: string

    :returns: the newly created yser
    :rtype: dictionary
    '''
    _check_access('user_invite', context, data_dict)

    schema = context.get('schema',
                         ckan.logic.schema.default_user_invite_schema())
    data, errors = _validate(data_dict, schema, context)
    if errors:
        raise ValidationError(errors)

    name = _get_random_username_from_email(data['email'])
    password = str(random.SystemRandom().random())
    data['name'] = name
    data['password'] = password
    data['state'] = ckan.model.State.PENDING
    user_dict = _get_action('user_create')(context, data)
    user = ckan.model.User.get(user_dict['id'])
    member_dict = {
        'username': user.id,
        'id': data['group_id'],
        'role': data['role']
    }
    _get_action('group_member_create')(context, member_dict)
    mailer.send_invite(user)
    return model_dictize.user_dictize(user, context)
Beispiel #23
0
    def test_send_invite_email(self):
        user = factories.User()
        user_obj = model.User.by_name(user['name'])
        assert user_obj.reset_key is None, user_obj

        # We need to provide a context as url_for is used internally
        with self.app.flask_app.test_request_context():
            # send email
            mailer.send_invite(user_obj)

            test_msg = mailer.get_invite_body(user_obj)

        # check it went to the mock smtp server
        msgs = self.get_smtp_messages()
        assert_equal(len(msgs), 1)
        msg = msgs[0]
        assert_equal(msg[1], config['smtp.mail_from'])
        assert_equal(msg[2], [user['email']])
        expected_body = self.mime_encode(test_msg, user['name'])

        assert_in(expected_body, msg[3])
        assert user_obj.reset_key is not None, user
Beispiel #24
0
    def account_requests_management(self):
        ''' Approve or reject an account request
        '''
        action = request.params['action']
        user_id = request.params['id']
        user_name = request.params['name']
        user = model.User.get(user_id)
        org = logic.get_action('organization_list_for_user')(
            {
                'user': user_name
            }, {
                'permission': 'read'
            })

        if org:
            user_delete = {
                'id': org[0]['name'],
                'object': user_name,
                'object_type': 'user'
            }

        context = {
            'model': model,
            'user': c.user,
            'session': model.Session,
        }
        activity_create_context = {
            'model': model,
            'user': user_name,
            'defer_commit': True,
            'ignore_auth': True,
            'session': model.Session
        }
        activity_dict = {'user_id': c.userobj.id, 'object_id': user_id}
        if action == 'forbid':
            object_id_validators['reject new user'] = user_id_exists
            activity_dict['activity_type'] = 'reject new user'
            logic.get_action('activity_create')(activity_create_context,
                                                activity_dict)
            # remove user, {{'user_email': user_email}}

            logic.get_action('user_delete')(context, {'id': user_id})
            msg = "Your account request for {0} has been rejected by {1}\n\nFor further clarification as to why your request has been rejected please contact the NSW Flood Data Portal ({2})".format(
                config.get('ckan.site_title'), c.userobj.fullname,
                config.get('ckanext.accessrequests.approver_email'))
            mailer.mail_recipient(user.fullname, user.email, 'Account request',
                                  msg)
            msg = "User account request for {0} has been rejected by {1}".format(
                user.fullname, c.userobj.fullname)
            mailer.mail_recipient(
                'Admin', config.get('ckanext.accessrequests.approver_email'),
                'Account request feedback', msg)
        elif action == 'approve':
            object_id_validators['approve new user'] = user_id_exists
            activity_dict['activity_type'] = 'approve new user'
            logic.get_action('activity_create')(activity_create_context,
                                                activity_dict)
            # Send invitation to complete registration
            msg = "User account request for {0} has been approved by {1}".format(
                user.fullname, c.userobj.fullname)
            mailer.mail_recipient(
                'Admin', config.get('ckanext.accessrequests.approver_email'),
                'Account request feedback', msg)
            try:
                mailer.send_invite(user)
            except Exception as e:
                log.error('Error emailing invite to user: %s', e)
                abort(500, _('Error: couldn' 't email invite to user'))

        response.status = 200
        return render('user/account_requests_management.html')
    def account_requests_management(self):
        ''' Approve or reject an account request
        '''
        action = request.params['action']
        user_id = request.params['id']
        user_name = request.params['name']
        user = model.User.get(user_id)

        context = {
            'model': model,
            'user': c.user,
            'session': model.Session,
        }
        activity_create_context = {
            'model': model,
            'user': user_name,
            'defer_commit': True,
            'ignore_auth': True,
            'session': model.Session
        }
        activity_dict = {'user_id': c.userobj.id, 'object_id': user_id}
        list_admin_emails = tk.aslist(
            config.get('ckanext.accessrequests.approver_email')
        )
        if action == 'forbid':
            object_id_validators['reject new user'] = user_id_exists
            activity_dict['activity_type'] = 'reject new user'
            logic.get_action('activity_create')(
                activity_create_context, activity_dict
            )
            org = logic.get_action('organization_list_for_user')({
                'user': user_name
            }, {
                "permission": "read"
            })
            if org:
                logic.get_action('organization_member_delete')(
                    context, {
                        "id": org[0]['id'],
                        "username": user_name
                    }
                )
            logic.get_action('user_delete')(context, {'id': user_id})
            msg = (
                "Your account request for {0} has been rejected by {1}"
                "\n\nFor further clarification "
                "as to why your request has been "
                "rejected please contact the NSW Flood Data Portal ({2})"
            )
            mailer.mail_recipient(
                user.fullname, user.email, 'Account request',
                msg.format(
                    config.get('ckan.site_title'), c.userobj.fullname,
                    c.userobj.email
                )
            )
            msg = ("User account request for {0} "
                   "has been rejected by {1}"
                   ).format(user.fullname or user_name, c.userobj.fullname)
            for admin_email in list_admin_emails:
                try:
                    mailer.mail_recipient(
                        'Admin', admin_email, 'Account request feedback', msg
                    )
                except mailer.MailerException as e:
                    h.flash(
                        "Email error: {0}".format(e.message), allow_html=False
                    )
        elif action == 'approve':
            user_org = request.params['org']
            user_role = request.params['role']
            object_id_validators['approve new user'] = user_id_exists
            activity_dict['activity_type'] = 'approve new user'
            logic.get_action('activity_create')(
                activity_create_context, activity_dict
            )
            org_display_name, org_role = assign_user_to_org(
                user_id, user_org, user_role, context
            )
            # Send invitation to complete registration
            msg = (
                "User account request for {0} "
                "(Organization : {1}, Role: {2}) "
                "has been approved by {3}"
            ).format(
                user.fullname or user_name, org_display_name, org_role,
                c.userobj.fullname
            )
            for admin_email in list_admin_emails:
                try:
                    mailer.mail_recipient(
                        'Admin', admin_email, 'Account request feedback', msg
                    )
                except mailer.MailerException as e:
                    h.flash(
                        "Email error: {0}".format(e.message), allow_html=False
                    )
            try:
                org_dict = tk.get_action('organization_show')(context, {'id': user_org})
                user.name = user.name
                mailer.send_invite(user, org_dict, user_role)
            except Exception as e:
                log.error('Error emailing invite to user: %s', e)
                abort(500, _('Error: couldn' 't email invite to user'))

        response.status = 200
        return render('user/account_requests_management.html')