def test_create_user():
    org_name2 = 'eorg'

    org = Organization.query.filter_by(full_name=org_name2).one()
    ciso_role = MembershipRole.query.filter_by(name='CISO').one()

    user_dict = {
        'name': 'testi 123',
        'email': '*****@*****.**',
        'password': '******',
        'birthdate': '1999-09-09',
    }

    (user, message) = User.create(user_dict)
    db.session.commit()
    assert user.id, 'User id set'
    assert message == 'User added', 'correct message'

    (user_alias, message) = User.create(user_dict)
    db.session.commit()
    assert user_alias.id, 'User id set'
    assert user_alias.alias_user_id, 'User alias id set'
    assert message == 'User aliased', 'correct message'

    organization_membership_dict = {
        'email': '*****@*****.**',
        'phone': '+43234234234',
        'membership_role_id': ciso_role.id,
        'organization_id': org.id,
        'user_id': user.id,
    }

    (organization_membership, message) = \
          OrganizationMembership.upsert(organization_membership_dict)
    db.session.commit()

    assert organization_membership.user_id == user.id, 'correct user set'
    assert organization_membership.user.name == 'testi 123', 'user name set'
    assert organization_membership.organization.full_name == org_name2, 'user name set'
    assert organization_membership.membership_role_id == ciso_role.id, 'role_id set'

    # create OrgAdmin
    admin_role = MembershipRole.query.filter_by(name='OrgAdmin').one()

    organization_membership_dict = {
        'email': '*****@*****.**',
        'phone': '+43234234234',
        'membership_role_id': admin_role.id,
        'organization_id': org.id,
        'user_id': user.id,
    }

    (organization_membership, message) = \
          OrganizationMembership.upsert(organization_membership_dict)
    db.session.commit()
    assert organization_membership.membership_role.name == 'OrgAdmin', 'role_id set'

    with pytest.raises(AttributeError):
        (organization_membership, message) = \
              OrganizationMembership.upsert(organization_membership_dict)
示例#2
0
def add():
    """Add sample data"""

    cert = Organization(
        abbreviation="CERT",
        full_name="CERT Master User",
    )
    db.session.add(cert)

    cert_user = User(name="cert master user", )
    cert_user.password = '******'
    db.session.add(cert_user)

    cert_user4cert = OrganizationMembership(email='*****@*****.**',
                                            zip='1234',
                                            organization=cert,
                                            user=cert_user)

    db.session.commit()

    click.echo('Done Org id: ' + str(cert.id))
    click.echo('Done User id: ' + str(cert_user.id))
    click.echo('adding sub org')

    eorg = Organization(abbreviation="E-Org",
                        full_name="E-Org Dach",
                        parent_org=cert)
    # db.session.add(eorg)

    eorg_user = User(name="eorg master user")
    eorg_user.password = '******'

    OrganizationMembership(email='*****@*****.**',
                           zip='5678',
                           organization=eorg,
                           user=eorg_user)

    eorg_electricity = Organization(abbreviation="E-Org Strom",
                                    full_name="E-Org Strom",
                                    parent_org=eorg)
    db.session.add(eorg_electricity)

    eorg_electricity_user = User(name="eorg electricity user", )
    eorg_electricity_user.password = '******'
    db.session.add(eorg_electricity_user)

    eorgelectricity_orguser = OrganizationMembership(
        email='*****@*****.**',
        zip='5678',
        organization=eorg_electricity,
        user=eorg_electricity_user)
    db.session.commit()
示例#3
0
def test_mark_as_deleted_aliasuser(client):
    user = User.query.filter_by(_name=TAU.rootuser_name).one()
    assert user, 'User not found.'

    alias = user.create_alias_user()
    assert user, 'alias not found.'

    org = Organization.query.filter_by(full_name=TAU.orgname).one()
    admin_role = MembershipRole.query.filter_by(name='OrgAdmin').one()
    oxu = OrganizationMembership(organization=org,
                                 user=alias,
                                 membership_role=admin_role)
    db.session.add(oxu)
    db.session.commit()

    try:
        alias.mark_as_deleted()
        db.session.commit()
    except:
        db.session.rollback()
        assert False, 'Test not possible. unexpected exception!'

    assert User.query.filter_by(alias_user_id=user.id).count(
    ) > 0, 'Test not possible, no aliases for user'

    for um in alias.user_memberships:
        assert alias.deleted == 1, 'User Membership of alias not marked as deleted'
示例#4
0
def test_create_rootuser(client):
    assert User.query.filter_by(_name=TAU.rootuser_name).first(
    ) == None, 'test broken. User found via query before insert.'

    newuser = User(name=TAU.rootuser_name)
    newuser.email = TAU.rootuser_email
    newuser.password = TAU.rootuser_password
    newuser.birthdate = datetime.datetime.utcnow()
    newuser.title = 'TestTitel.'
    newuser.origin = 'testDS'
    db.session.add(newuser)

    org = Organization.query.filter_by(abbreviation=TAU.org1_abbr).one()
    admin_role = MembershipRole.query.filter_by(name='OrgAdmin').one()
    oxu = OrganizationMembership(organization=org,
                                 user=newuser,
                                 membership_role=admin_role)
    db.session.add(oxu)

    db.session.commit()

    #test queries user
    user = User.query.filter_by(_name=TAU.rootuser_name).first()
    assert user, 'User not found via query'
    assert OrganizationMembership.query.filter_by(
        user_id=user.id).count() == 1, 'No Memberships found for user_id'
    assert OrganizationMembership.query.filter_by(
        user=user).count() == 1, 'No Memberships found for user object'

    #test user authenticate
    (admin, auth) = User.authenticate(TAU.rootuser_email,
                                      TAU.rootuser_password)
    assert auth is True, 'User cant log in'
    assert len(admin.get_users()) == 1, 'wrong number of users'
示例#5
0
def test_delete_aliasuser(client):
    user = User.query.filter_by(_name=TAU.rootuser_name).one()
    assert user, 'test broken. User not found.'

    alias = user.create_alias_user()
    assert user, 'test broken. alias not found.'

    org = Organization.query.filter_by(full_name=TAU.orgname).one()
    admin_role = MembershipRole.query.filter_by(name='OrgAdmin').one()
    oxu = OrganizationMembership(organization=org,
                                 user=alias,
                                 membership_role=admin_role)
    db.session.add(oxu)
    db.session.commit()

    assert OrganizationMembership.query.filter_by(user_id=alias.id).count(
    ) > 0, 'OrganizationMembership for alias was not created'

    #exception fur test not important.
    try:
        User.query.filter_by(id=alias.id).delete()
        db.session.commit()
    except:
        db.session.rollback()

    assert User.query.filter_by(
        id=alias.id).count() == 0, 'alias has not been deleted'

    assert OrganizationMembership.query.filter_by(user_id=alias.id).count(
    ) == 0, 'OrganizationMembership not deleted, when alias user of that membership was deleted.'
def update_cp_organization_membership(membership_id):
    """Update organization membership details"""

    existing_membership = OrganizationMembership.query.filter(
        OrganizationMembership.id == membership_id).first()

    if not existing_membership:
        return redirect(url_for('cp.add_cp_organization_membership'))

    check_membership_permissions(existing_membership)

    try:
        (membership,
         message) = OrganizationMembership.upsert(request.json,
                                                  existing_membership)
        check_membership_permissions(membership)
    except AttributeError as ae:
        db.session.rollback()
        message = 'Attribute error. Invalid email, phone or mobile? ' + str(ae)
        return ApiResponse({
            'message': message,
        }, 422, {})
    except Exception as ae:
        db.session.rollback()
        message = "something went wrong, please contact admin: " + str(ae)
        return ApiResponse({
            'message': message,
        }, 418, {})

    db.session.commit()
    return ApiResponse({'message': message})
示例#7
0
def test_create_aliasuser(client):
    user = User.query.filter_by(_name=TAU.rootuser_name).first()

    alias = user.create_alias_user()
    org = Organization.query.filter_by(abbreviation=TAU.org2_abbr).one()
    admin_role = MembershipRole.query.filter_by(name='OrgAdmin').one()
    oxu = OrganizationMembership(organization=org,
                                 user=alias,
                                 membership_role=admin_role)
    db.session.add(oxu)
    db.session.commit()

    alias = user.create_alias_user()
    org = Organization.query.filter_by(abbreviation=TAU.org31_abbr).one()
    admin_role = MembershipRole.query.filter_by(name='OrgAdmin').one()
    oxu = OrganizationMembership(organization=org,
                                 user=alias,
                                 membership_role=admin_role)
    db.session.add(oxu)
    db.session.commit()

    assert User.query.filter_by(
        alias_user_id=user.id).count() == 2, 'wrong count for testalias'
示例#8
0
def test_create_orgadmin():
    newuser = User(name='test_org admin ')
    newuser.email = '*****@*****.**'
    newuser.password = '******'
    newuser.birthdate = datetime.datetime.utcnow()
    newuser.title = 'DDDr. hc. mult.'
    newuser.origin = 'your mother'

    org = Organization.query.filter_by(full_name='eorg').one()

    admin_role = MembershipRole.query.filter_by(name='OrgAdmin').one()
    oxu = OrganizationMembership(organization=org,
                                 user=newuser,
                                 membership_role=admin_role)
    db.session.add(oxu)
    db.session.add(newuser)
    db.session.commit()
    assert newuser.api_key, 'api key is set'
示例#9
0
def test_authenticate_alias(client):
    query = User.query.filter_by(alias_user_id=None)
    assert query.count() > 0, 'test not possible. no aliases found'
    for alias in query.all():
        if OrganizationMembership.query.filter_by(
                user_id=alias.id).count() == 0:
            org = Organization.query.filter_by(full_name=TAU.orgname).one()
            admin_role = MembershipRole.query.filter_by(name='OrgAdmin').one()
            oxu = OrganizationMembership(organization=org,
                                         user=alias,
                                         membership_role=admin_role)
            db.session.add(oxu)
            db.session.commit()
    (alias, auth) = User.authenticate(None, TAU.alias_password)
    assert auth == False, '[security] authenticate possibe for alias.'
    assert alias == None, '[security] authenticate possibe for alias.'
    (alias, auth) = User.authenticate('', TAU.alias_password)
    assert auth == False, '[security] authenticate possibe for alias.'
    assert alias == None, '[security] authenticate possibe for alias.'
示例#10
0
def test_create_alias_user():
    u = User.query.filter_by(_name='eorgmaster').first()
    alias_user = u.create_alias_user()
    # print("\n" + alias_user.name + "\n")
    role = MembershipRole.query.filter_by(name='CISO').first()
    energy_org = Organization.query.filter_by(abbreviation='energyorg').one()
    oxu = OrganizationMembership(phone='+123214711',
                                 mobile='+12321312',
                                 email='*****@*****.**',
                                 organization=energy_org,
                                 user=alias_user,
                                 membership_role=role,
                                 pgp_key_id='asdasdasd',
                                 pgp_key_fingerprint='ADFEFEF123123',
                                 pgp_key='asdasasfasfasf',
                                 smime='asdasdasd',
                                 coc=b'asasda')
    db.session.add(oxu)
    db.session.commit()
def add_cp_organization_membership():
    """Add new organization membership

    :>json string message: Status message
    :>json integer id: Organization membership ID

    :status 200: Organization membership details were successfully saved

    :status 400: Bad request
    :status 401: Authorization failure. The client MAY repeat the request with
        a suitable API-Authorization header field. If the request already
        included Authorization credentials, then the 401 response indicates

        that authorization has been refused for those credentials.
    :status 403: Access denied. Authorization will not help and the request
        SHOULD NOT be repeated.
    :status 422: Validation error
    """
    try:
        (membership, message) = OrganizationMembership.upsert(request.json)
        check_membership_permissions(membership)
    except AttributeError as ae:
        message = 'Attribute error. Invalid email, phone or mobile?'
        return ApiResponse({
            'message': message,
        }, 422, {})
    except Exception as ae:
        message = "something went wrong, please contact admin: " + str(ae)
        return ApiResponse({
            'message': message,
        }, 418, {})

    db.session.commit()
    return  ApiResponse({'organization_membership': membership.serialize(),
            'message': message}, 201, \
           {'Location': url_for('cp.get_cp_organization_membership',
                                membership_id=membership.id)})
示例#12
0
def test_create_rootuser(client):
    #test user noch nicht angelegt
    assert User.query.filter_by(_name=TAU.rootuser_name).first(
    ) == None, 'User found via query before insert.'

    newuser = User(name=TAU.rootuser_name)
    newuser.email = TAU.rootuser_email
    newuser.password = TAU.rootuser_password
    newuser.birthdate = datetime.datetime.utcnow()
    newuser.title = 'TestTitel.'
    newuser.origin = 'testDS'
    db.session.add(newuser)

    org = Organization.query.filter_by(abbreviation=TAU.org1_abbr).one()
    admin_role = MembershipRole.query.filter_by(name='OrgAdmin').one()
    oxu = OrganizationMembership(organization=org,
                                 user=newuser,
                                 membership_role=admin_role)
    db.session.add(oxu)

    db.session.commit()

    #test queries auf user
    user = User.query.filter_by(_name=TAU.rootuser_name).first()
    assert user, 'User not found via query'
    assert OrganizationMembership.query.filter_by(
        user_id=user.id).count() == 1, 'No Memberships found for user_id'
    assert OrganizationMembership.query.filter_by(
        user=user).count() == 1, 'No Memberships found for user object'

    #test user authenticate moeglich
    (admin, auth) = User.authenticate(TAU.rootuser_email,
                                      TAU.rootuser_password)
    assert auth is True, 'User cant log in'

    #test zugriff nur auf einen user, da neue org und dazu neuer user
    assert len(admin.get_users()) == 1, 'Falsche Anzahl User zum neuen User'
示例#13
0
def add_cp_user():
    """Add new user

    **Example request**:

    .. sourcecode:: http

        POST /api/1.0/users HTTP/1.1
        Host: do.cert.europa.eu
        Accept: application/json
        Content-Type: application/json

        {
          "login": "******",
          "password": "******",
          "name": "Max Muster",
          "picture": "image/png;base64,iVBORw0KGgoAAAANS...",
          "birthdate": "1951-03-22",
          "title": "Dr.",
          "origin": "Uranus",
          "membership_role_id": 12,
          "organization_id": 201
        }

    **Example response**:

    .. sourcecode:: http

        HTTP/1.0 201 CREATED
        Content-Type: application/json

        {
          "message": "User saved"
        }

    **Example validation error**:

    .. sourcecode:: http

        HTTP/1.0 400 BAD REQUEST
        Content-Type: application/json

        {
          "message": "'name' is a required property",
          "validator": "required"
        }

    :reqheader Accept: Content type(s) accepted by the client
    :reqheader API-Authorization: API key. If present authentication and
            authorization will be attempted.
    :resheader Content-Type: This depends on `Accept` header or request

    :<json string login: Login email address. If not present, the user can't
            login
    :<json string password: Password
    :<json string name: Name
    :<json string picture: Base64-encoded PNG profile picture
    :<json string birthdate: Birthdate as YYYY-MM-DD
    :<json string title: Academic or honorific title
    :<json string origin: Origin
    :<json integer membership_role_id: Unique ID of the organization user role
    :<json integer organization_id: Unique ID of the organization
    :<json string country_id: Unique ID of the country
    :<json string street: Street address
    :<json string zip: Zip code
    :<json string phone: Phone number
    :<json string email: Email address
    :<json string comment: Arbitrary comment
    :<json string pgp_key_id: PGP key ID
    :<json string pgp_key_fingerprint: PGP key fingerprint
    :<json string pgp_key: PGP key
    :<json string smime: S/MIME
    :<json string coc: Code of Conduct

    :>json string message: Status message
    :>json integer id: User ID

    :status 200: User details were successfully saved
    :status 400: Bad request
    :status 401: Authorization failure. The client MAY repeat the request with
        a suitable API-Authorization header field. If the request already
        included Authorization credentials, then the 401 response indicates
        that authorization has been refused for those credentials.
    :status 403: Access denied. Authorization will not help and the request
        SHOULD NOT be repeated.
    """
    try:
        user = User.fromdict(request.json['user'])
        membership = OrganizationMembership.fromdict(
            request.json['organization_membership'])
    except AttributeError as ae:
        return ApiResponse(
            {
                'message':
                'Attribute error. Invalid email, phone or mobile?' + str(ae),
            }, 422, {})

    # The role and organization must exist and the current user must be able to
    # admin the organization.

    role = MembershipRole.query.get_or_404(membership.membership_role_id)
    org = Organization.query.get_or_404(membership.organization_id)
    if not g.user.may_handle_organization(org):
        abort(403)

    db.session.add(user)
    db.session.commit()

    membership.user_id = user.id
    db.session.add(membership)
    db.session.commit()
    return ApiResponse({'user': user.serialize(),
            'organization_membership': membership.serialize(),
            'message': 'User added'}, 201, \
           {'Location': url_for('cp.get_cp_user', user_id=user.id)})
示例#14
0
    def addyaml(yamlfile="install/testdata.yaml"):
        """Add sample data from yaml file"""
        with open(yamlfile, 'r') as stream:
            data_loaded = yaml.load(stream)

        for org in data_loaded['org']:
            if 'full_name' not in org:
                org['full_name'] = org['abbreviation']
            if 'display_name' not in org:
                org['display_name'] = org['abbreviation']
            o = Organization(
                abbreviation=org['abbreviation'],
                full_name=org['full_name'],
                display_name=org['display_name'],
            )
            if ('parent_org' in org):
                po = Organization.query.filter_by(
                    abbreviation=org['parent_org']).first()
                o.parent_org = po
            db.session.add(o)
            db.session.commit()

        for user in data_loaded['user']:
            u = User.query.filter_by(name=user['name']).first()
            if (not u):
                u = User(name=user['name'])
                u.email = user['email']
                u.api_key = u.generate_api_key()
                if 'password' in user:
                    u.password = user['password']
                else:
                    u.password = '******'
                db.session.add(u)

            role = MembershipRole.query.filter_by(name=user['role']).first()
            org = Organization.query.filter_by(
                abbreviation=user['org']).first()
            if 'email' not in user:
                user['email'] = '*****@*****.**'
            if 'street' not in user:
                user['street'] = 'no street'
            if 'zip' not in user:
                user['zip'] = '1234'
            if 'city' not in user:
                user['city'] = 'n/a'
            if 'country' not in user:
                country_o = Country.query.filter_by(cc='AT').first()
            else:
                country_o = Country.query.filter_by(cc=user['country']).first()
            if 'comment' not in user:
                user['comment'] = 'no comment'
            if 'phone' not in user:
                user['phone'] = '+12345678'
            if 'mobile' not in user:
                user['mobile'] = '+33456788'
            if 'sms_alerting' not in user:
                user['sms_alerting'] = 0

            oxu = OrganizationMembership(
                email=user['email'],
                street=user['street'],
                city=user['city'],
                zip=user['zip'],
                country=country_o,
                comment=user['comment'],
                phone=user['phone'],
                mobile=user['mobile'],
                organization=org,
                user=u,
                membership_role=role,
                sms_alerting=user['sms_alerting'],
            )
            db.session.commit()
示例#15
0
def test_contact_abusec():
    # https://github.com/certat/do-portal/wiki
    # GET /api/v1/contact?netblock=1.2.3.0/24
    # Get the direct abuse_c which holds the netblock 1.2.3.0/24 and only this abuse_c

    # cidr has settings, no local abusec
    cidr = '94.245.192.0/18'
    notification = NotificationSetting.contact_for_netblock(cidr)
    assert notification['abusecs'][0] == '*****@*****.**', 'abusec from ripe'
    assert notification['notification_setting'][
        'delivery_format'] == 'JSON', 'setting from cidr'
    assert notification['notification_setting'][
        'notification_interval'] == 47, 'setting from cidr'
    assert notification['notification_setting'][
        'organization_id'] == 1, 'setting from cidr'
    assert notification['notification_setting'][
        'ripe_org_hdl'] == 'ORG-CAGF1-RIPE', 'cidr'

    pprint(notification)

    # cidr has no settings but owning ripe handle is associated with an organization
    cidr = '2001:4b68::/29'
    notification = NotificationSetting.contact_for_netblock(cidr)
    pprint(notification)
    assert notification['abusecs'][0] == '*****@*****.**', 'abusec from ripe'
    assert notification['notification_setting'][
        'delivery_format'] == 'CSV', 'default'
    assert notification['notification_setting'][
        'notification_interval'] == 604800, 'default'
    assert notification['notification_setting'][
        'organization_id'] == 1, 'setting from cidr'
    assert notification['notification_setting'][
        'ripe_org_hdl'] == 'ORG-CAGF1-RIPE', 'cidr'

    # remember org_id to create a abusec later
    organization_id = notification['notification_setting']['organization_id']

    # not found
    cidr = '1.1.1.1'
    with pytest.raises(AttributeError):
        notification = NotificationSetting.contact_for_netblock(cidr)

    # cidr not associated with org
    cidr = '2a03:8a80::/32'
    notification = NotificationSetting.contact_for_netblock(cidr)
    pprint(notification)
    assert notification['abusecs'][
        0] == '*****@*****.**', 'abusec from ripe'
    assert notification['notification_setting'][
        'delivery_format'] == 'CSV', 'default'
    assert notification['notification_setting'][
        'notification_interval'] == 604800, 'default'
    assert notification['notification_setting'][
        'organization_id'] is None, 'no org found'
    assert notification['notification_setting'][
        'ripe_org_hdl'] is None, 'no org found'

    # create abusec for created org
    abusec_role = MembershipRole.query.filter_by(name='abuse-c').one()
    eorg_user = User.query.filter_by(name='eorgmaster').one()
    oxu = OrganizationMembership(
        user=User.query.filter_by(name='eorgmaster').one(),
        membership_role=MembershipRole.query.filter_by(name='abuse-c').one(),
        organization=Organization.get(organization_id),
        email='*****@*****.**')

    db.session.add(oxu)
    db.session.commit()
    cidr = '94.245.192.0/18'
    notification = NotificationSetting.contact_for_netblock(cidr)
    pprint(notification)
    assert notification['abusecs'][
        0] == '*****@*****.**', 'abusec local'
    assert notification['notification_setting'][
        'delivery_format'] == 'JSON', 'setting from cidr'
    assert notification['notification_setting'][
        'notification_interval'] == 47, 'setting from cidr'
    assert notification['notification_setting'][
        'organization_id'] == 1, 'setting from cidr'
    assert notification['notification_setting'][
        'ripe_org_hdl'] == 'ORG-CAGF1-RIPE', 'cidr'

    # cidr has no settings but owning ripe handle is associated with an organization
    cidr = '2001:4b68::/29'
    notification = NotificationSetting.contact_for_netblock(cidr)
    pprint(notification)
    assert notification['abusecs'][
        0] == '*****@*****.**', 'abusec local'
    assert notification['notification_setting'][
        'delivery_format'] == 'CSV', 'default'
    assert notification['notification_setting'][
        'notification_interval'] == 604800, 'default'
    assert notification['notification_setting'][
        'organization_id'] == 1, 'setting from cidr'
    assert notification['notification_setting'][
        'ripe_org_hdl'] == 'ORG-CAGF1-RIPE', 'cidr'
示例#16
0
def test_create_user():
    """
    + get user who we know is an admin
    + get org for this user
    + get some other org (certorg)

    + create new user
    + try to
    """

    admin = User.query.filter_by(name="EnergyOrg Admin").first()
    assert len(admin.user_memberships) == 1
    org = admin.get_organizations().first()

    c = len(admin.get_users())
    assert c == 3, 'Verbung Admin has 3 users'
    certorg = Organization.query.filter_by(abbreviation='cert').first()

    newuser = User(name=App.username)
    with pytest.raises(AttributeError):
        newuser.email = 'testbla.com'
    newuser.email = '*****@*****.**'
    newuser.password = '******'
    newuser.picture = b'asasda'
    newuser.birthdate = datetime.datetime.utcnow()
    newuser.title = 'DDDr. hc. mult.'
    newuser.origin = 'your mother'
    db.session.add(newuser)
    db.session.commit()
    assert newuser.id > 0
    assert admin.may_handle_organization(certorg) is False, \
        'energyorg admin may not handle cert org'
    assert admin.may_handle_organization(org) is True

    role = MembershipRole.query.filter_by(name='CISO').first()
    with pytest.raises(AttributeError):
        oxu = OrganizationMembership(phone='+43434711',
                                     email='asdaddasd.at',
                                     organization=org,
                                     user=newuser,
                                     membership_role=role,
                                     pgp_key_id='asdasdasd',
                                     pgp_key_fingerprint='ADFEFEF123123',
                                     pgp_key='asdasasfasfasf',
                                     smime='asdasdasd',
                                     coc=b'asasda')
    oxu = OrganizationMembership(phone='+123214711',
                                 mobile='+12321312',
                                 email='*****@*****.**',
                                 organization=org,
                                 user=newuser,
                                 membership_role=role,
                                 pgp_key_id='asdasdasd',
                                 pgp_key_fingerprint='ADFEFEF123123',
                                 pgp_key='asdasasfasfasf',
                                 smime='asdasdasd',
                                 coc=b'asasda')
    db.session.add(oxu)
    db.session.commit()
    assert oxu.id > 0, 'OrganizationMembership written'
    assert len(admin.get_users()) == 4, 'EnergyOrg Admin now has 4 users'
    App.user = newuser
def add_cp_organization_membership():
    """Add new organization membership

    **Example request**:

    .. sourcecode:: http

        POST /api/1.0/organization_memberships HTTP/1.1
        Host: do.cert.europa.eu
        Accept: application/json
        Content-Type: application/json

        {
          "membership_role_id": 12,
          "user_id": 153,
          "organization_id": 201,
          "country_id": 23,
          "street": "Mustergasse 2/4",
          "zip": "1234",
          "phone": "+4315671234",
          "email": "*****@*****.**",
          "comment": "foo",
          "pgp_key_id": "abc123",
          "pgp_key_fingerprint": "def456",
          "pgp_key": "ghi789",
          "smime": "something",
          "coc": "anythnig goes"
        }

    **Example response**:

    .. sourcecode:: http

        HTTP/1.0 201 CREATED
        Content-Type: application/json

        {
          "message": "Organization saved"
        }

    **Example validation error**:

    .. sourcecode:: http

        HTTP/1.0 400 BAD REQUEST
        Content-Type: application/json

        {
          "message": "'membership_role_id' is a required property",
          "validator": "required"
        }

    :reqheader Accept: Content type(s) accepted by the client
    :reqheader API-Authorization: API key. If present authentication and
            authorization will be attempted.
    :resheader Content-Type: This depends on `Accept` header or request

    :<json integer membership_role_id: Unique ID of the organization user role
    :<json integer user_id: Unique ID of the user
    :<json integer organization_id: Unique ID of the organization
    :<json string country_id: Unique ID of the country
    :<json string street: Street address
    :<json string zip: Zip code
    :<json string phone: Phone number
    :<json string email: Email address
    :<json string comment: Arbitrary comment
    :<json string pgp_key_id: PGP key ID
    :<json string pgp_key_fingerprint: PGP key fingerprint
    :<json string pgp_key: PGP key
    :<json string smime: S/MIME
    :<json string coc: Code of Conduct

    :>json string message: Status message
    :>json integer id: Organization membership ID

    :status 200: Organization membership details were successfully saved
    :status 400: Bad request
    :status 401: Authorization failure. The client MAY repeat the request with
        a suitable API-Authorization header field. If the request already
        included Authorization credentials, then the 401 response indicates
        that authorization has been refused for those credentials.
    :status 403: Access denied. Authorization will not help and the request
        SHOULD NOT be repeated.
    :status 422: Validation error
    """
    try:
        membership = OrganizationMembership.fromdict(request.json)
    except AttributeError:
        return ApiResponse(
            {
                'message': 'Attribute error. Invalid email, phone or mobile?',
            }, 422, {})

    check_membership_permissions(membership)
    db.session.add(membership)
    db.session.commit()
    return  ApiResponse({'organization_membership': membership.serialize(),
            'message': 'Organization membership added'}, 201, \
           {'Location': url_for('cp.get_cp_organization_membership',
                                membership_id=membership.id)})