Exemple #1
0
def callback():
    resp = oauth_provider.authorized_response()
    if resp is None or isinstance(resp, OAuthException):
        log.warning("Failed OAuth: %r", resp)
        # FIXME: notify the user, somehow.
        return redirect(url_for('base_api.ui'))

    session['oauth'] = resp
    session['roles'] = [Role.system(Role.SYSTEM_USER)]
    if 'googleapis.com' in oauth_provider.base_url:
        me = oauth_provider.get('userinfo')
        user_id = 'google:%s' % me.data.get('id')
        role = Role.load_or_create(user_id, Role.USER, me.data.get('name'),
                                   email=me.data.get('email'))
    elif 'occrp.org' in oauth_provider.base_url or \
            'investigativedashboard.org' in oauth_provider.base_url:
        me = oauth_provider.get('api/2/accounts/profile/')
        user_id = 'idashboard:user:%s' % me.data.get('id')
        role = Role.load_or_create(user_id, Role.USER,
                                   me.data.get('display_name'),
                                   email=me.data.get('email'),
                                   is_admin=me.data.get('is_admin'))
        for group in me.data.get('groups', []):
            group_id = 'idashboard:%s' % group.get('id')
            group_role = Role.load_or_create(group_id, Role.GROUP,
                                             group.get('name'))
            session['roles'].append(group_role.id)
    else:
        raise RuntimeError("Unknown OAuth URL: %r" % oauth_provider.base_url)
    session['roles'].append(role.id)
    session['user'] = role.id
    db.session.commit()
    log.info("Logged in: %r", role)
    return redirect(url_for('base_api.ui'))
Exemple #2
0
def create():
    require(not request.authz.in_maintenance, settings.PASSWORD_LOGIN)
    data = parse_request(RoleCreateSchema)

    try:
        email = Role.SIGNATURE.loads(data.get('code'),
                                     max_age=Role.SIGNATURE_MAX_AGE)
    except BadSignature:
        return jsonify({
            'status': 'error',
            'message': gettext('Invalid code')
        }, status=400)

    role = Role.by_email(email)
    if role is not None:
        return jsonify({
            'status': 'error',
            'message': gettext('Email is already registered')
        }, status=409)

    role = Role.load_or_create(
        foreign_id='password:{}'.format(email),
        type=Role.USER,
        name=data.get('name') or email,
        email=email
    )
    role.set_password(data.get('password'))
    db.session.add(role)
    db.session.commit()
    update_role(role)
    # Let the serializer return more info about this user
    request.authz.id = role.id
    tag_request(role_id=role.id)
    return RoleSerializer.jsonify(role, status=201)
Exemple #3
0
def handle_keycloak_oauth(sender, provider=None, oauth=None):
    from aleph.model import Role
    superuser_role = 'superuser'

    if 'secure.occrp.org' not in provider.base_url:
        return

    access_token = oauth.get('access_token')
    token_data = jwt.decode(access_token, verify=False)
    clients = token_data.get('resource_access', {})
    client = clients.get(provider.consumer_key, {})
    roles = set(client.get('roles', []))
    is_admin = superuser_role in roles

    user_id = 'kc:%s' % token_data.get('email')
    if token_data.get('idashboard'):
        user_id = 'idashboard:user:%s' % token_data.get('idashboard')
    role = Role.load_or_create(user_id, Role.USER,
                               token_data.get('name'),
                               email=token_data.get('email'),
                               is_admin=is_admin)
    role.clear_roles()
    for role_name in roles:
        group_role = Role.load_or_create('kc:%s' % role_name,
                                         Role.GROUP,
                                         role_name)
        role.add_role(group_role)
        log.debug("User %r is member of %r", role, group_role)
    return role
Exemple #4
0
    def from_role(cls, role):
        roles = set([Role.load_id(Role.SYSTEM_GUEST)])
        if role is None:
            return cls(None, roles)

        roles.add(role.id)
        roles.add(Role.load_id(Role.SYSTEM_USER))
        roles.update([g.id for g in role.roles])
        return cls(role.id, roles, is_admin=role.is_admin)
Exemple #5
0
 def login(self, foreign_id='tester', name=None, email=None,
           is_admin=False):
     role = self.create_user(foreign_id=foreign_id, name=name, email=email,
                             is_admin=is_admin)
     with self.client.session_transaction() as sess:
         sess['roles'] = [Role.system(Role.SYSTEM_GUEST),
                          Role.system(Role.SYSTEM_USER), role.id]
         sess['user'] = role.id
     return role
Exemple #6
0
def get_public_roles():
    app = current_app._get_current_object()
    if not hasattr(app, '_public_roles') or not len(app._public_roles):
        roles = [
            Role.by_foreign_id(Role.SYSTEM_GUEST),
            Role.by_foreign_id(Role.SYSTEM_USER)
        ]
        app._public_roles = [r.id for r in roles if r is not None]
    return app._public_roles
Exemple #7
0
def cleanup_deleted():
    from aleph.model import Alert, Entity, Collection
    from aleph.model import Permission, Role
    Alert.cleanup_deleted()
    Permission.cleanup_deleted()
    Entity.cleanup_deleted()
    Collection.cleanup_deleted()
    Role.cleanup_deleted()
    db.session.commit()
Exemple #8
0
def system_role(role_name):
    from aleph.model import Role
    if not hasattr(app, '_authz_roles'):
        app._authz_roles = {}
        role = Role.load_or_create(Role.SYSTEM_GUEST, Role.SYSTEM,
                                   'All visitors')
        app._authz_roles[Role.SYSTEM_GUEST] = role.id
        role = Role.load_or_create(Role.SYSTEM_USER, Role.SYSTEM,
                                   'Logged-in users')
        app._authz_roles[Role.SYSTEM_USER] = role.id
        db.session.commit()
    return app._authz_roles.get(role_name)
Exemple #9
0
def check_alerts():
    for role_id, in Role.notifiable():
        with current_app.test_request_context('/'):
            role = Role.by_id(role_id)
            request.auth_role = role
            request.logged_in = True
            # FIXME: can't re-gain access to implicit oauth rules.
            # -> https://github.com/pudo/aleph/issues/14
            request.auth_roles = [Role.system(Role.SYSTEM_USER),
                                  Role.system(Role.SYSTEM_GUEST),
                                  role.id]
            check_role_alerts(role)
Exemple #10
0
def create():
    require(request.authz.logged_in)
    data = parse_request(CollectionCreateSchema)
    role = Role.by_id(request.authz.id)
    sync = get_flag('sync')
    collection = create_collection(data, role=role, sync=sync)
    return CollectionSerializer.jsonify(collection)
Exemple #11
0
def index(id):
    collection = get_db_collection(id, request.authz.WRITE)
    record_audit(Audit.ACT_COLLECTION, id=id)
    roles = [r for r in Role.all_groups() if check_visible(r, request.authz)]
    q = Permission.all()
    q = q.filter(Permission.collection_id == collection.id)
    permissions = []
    for permission in q.all():
        if not check_visible(permission.role, request.authz):
            continue
        permissions.append(permission)
        if permission.role in roles:
            roles.remove(permission.role)

    # this workaround ensures that all groups are visible for the user to
    # select in the UI even if they are not currently associated with the
    # collection.
    for role in roles:
        if collection.casefile and role.is_public:
            continue
        permissions.append({
            'collection_id': collection.id,
            'write': False,
            'read': False,
            'role_id': str(role.id)
        })

    permissions = PermissionSerializer().serialize_many(permissions)
    return jsonify({
        'total': len(permissions),
        'results': permissions
    })
Exemple #12
0
def view(id):
    authz.require(authz.logged_in())
    role = obj_or_404(Role.by_id(id))
    data = role.to_dict()
    if role.id != request.auth_role.id:
        del data["email"]
    return jsonify(data)
Exemple #13
0
def handle_azure_oauth(sender, provider=None, oauth=None):
    from aleph.model import Role
    if 'login.microsoftonline.com' not in provider.base_url:
        return

    # Get incoming token, extract header for use with certificate verification
    id_token = oauth.get('id_token')
    headerbit = id_token.split('.')[0]
    headerbit = base64.b64decode(headerbit).decode('utf8')
    headerbit = json.loads(headerbit)

    # Load cert from MS - can be cached for upwards of 24hrs, not done now
    cert_loc = 'https://login.microsoftonline.com/common/discovery/keys'
    cert_data = json.loads(urlopen(cert_loc).read())
    pemstart = "-----BEGIN CERTIFICATE-----\n"
    pemend = "\n-----END CERTIFICATE-----\n"
    # Find correct cert based on header
    for key in cert_data['keys']:
        if headerbit['kid'] == key['kid'] and headerbit['x5t'] == key['x5t']:
            mspubkey = key['x5c'][0]
            break
    cert_str = pemstart + mspubkey + pemend
    cert_obj = load_pem_x509_certificate(cert_str.encode('ascii'),
                                         default_backend())
    public_key = cert_obj.public_key()

    # Decode incoming token and verify against the MS cert
    token_data = jwt.decode(id_token, public_key, verify=True,
                            audience=settings.OAUTH_KEY)

    # All Ok, move on
    user_id = 'azure:%s' % token_data['upn']
    return Role.load_or_create(user_id, Role.USER, token_data['name'],
                               email=token_data['upn'])
Exemple #14
0
def index():
    authz.require(authz.logged_in())
    users = []
    for role in Role.all():
        data = role.to_dict()
        del data["email"]
        users.append(data)
    return jsonify({"results": users, "total": len(users)})
Exemple #15
0
 def create_user(self, foreign_id='tester', name=None, email=None,
                 is_admin=False):
     role = Role.load_or_create(foreign_id, Role.USER,
                                name or foreign_id,
                                email=email or self.fake.email(),
                                is_admin=is_admin)
     db.session.commit()
     return role
Exemple #16
0
def update(id):
    role = obj_or_404(Role.by_id(id))
    authz.require(authz.logged_in())
    authz.require(role.id == request.auth_role.id)
    role.update(request_data())
    db.session.add(role)
    db.session.commit()
    return jsonify(role)
Exemple #17
0
def index():
    authz.require(authz.logged_in())
    users = []
    for role in Role.all():
        data = role.to_dict()
        del data['email']
        users.append(data)
    return jsonify({'results': users, 'total': len(users)})
Exemple #18
0
def index():
    require(request.authz.logged_in)
    role = Role.by_id(request.authz.id)
    query = Notification.by_channels(get_role_channels(role),
                                     since=role.notified_at,
                                     exclude_actor_id=role.id)
    result = DatabaseQueryResult(request, query)
    return NotificationSerializer.jsonify_result(result)
Exemple #19
0
 def grant_foreign(cls, resource, foreign_id, read, write):
     from aleph.model import Source, Watchlist, Role
     role = Role.by_foreign_id(foreign_id)
     if role is None:
         return
     if isinstance(resource, Source):
         cls.grant_resource(cls.SOURCE, resource.id, role, read, write)
     if isinstance(resource, Watchlist):
         cls.grant_resource(cls.WATCHLIST, resource.id, role, read, write)
Exemple #20
0
 def grant_foreign(cls, resource, foreign_id, read, write):
     from aleph.model import Source, Collection, Role
     role = Role.by_foreign_id(foreign_id)
     if role is None:
         return
     if isinstance(resource, Source):
         cls.grant_resource(cls.SOURCE, resource.id, role, read, write)
     if isinstance(resource, Collection):
         cls.grant_resource(cls.COLLECTION, resource.id, role, read, write)
Exemple #21
0
def update(id):
    role = obj_or_404(Role.by_id(id))
    require(request.authz.session_write)
    require(check_editable(role, request.authz))
    data = parse_request(RoleSchema)
    role.update(data)
    db.session.add(role)
    db.session.commit()
    update_role(role)
    return RoleSerializer.jsonify(role)
Exemple #22
0
 def test_load_or_create_role_exists(self):
     self.assertEqual(
         Role.load_or_create(
             foreign_id=self.role.foreign_id,
             type=self.role.type,
             name=self.role.name,
             email=self.role.email
         ),
         self.role
     )
Exemple #23
0
def handle_google_oauth(sender, provider=None, oauth=None):
    from aleph.model import Role
    if 'googleapis.com' not in provider.base_url:
        return

    token = (oauth.get('access_token'), '')
    me = provider.get('userinfo', token=token)
    user_id = 'google:%s' % me.data.get('id')
    return Role.load_or_create(user_id, Role.USER, me.data.get('name'),
                               email=me.data.get('email'))
Exemple #24
0
def handle_facebook_oauth(sender, provider=None, oauth=None):
    from aleph.model import Role
    if 'facebook.com' not in provider.base_url:
        return

    token = (oauth.get('access_token'), '')
    me = provider.get('me?fields=id,name,email', token=token)
    user_id = 'facebook:%s' % me.data.get('id')
    return Role.load_or_create(user_id, Role.USER, me.data.get('name'),
                               email=me.data.get('email'))
Exemple #25
0
def invite_email():
    data = parse_request(schema=RoleInviteSchema)
    signature = Role.SIGNATURE.dumps(data['email'])
    url = '{}signup/{}'.format(app_url, signature)
    role = Role(email=data['email'], name='Visitor')
    notify_role_template(role, 'Registration',
                         'email/registration_invitation.html',
                         url=url)
    return jsonify({
        'status': 'ok',
        'message': 'To proceed, please check your email.'
    })
Exemple #26
0
def create_collection(data, role=None, sync=False):
    role = role or Role.load_cli_user()
    created_at = datetime.utcnow()
    collection = Collection.create(data, role=role, created_at=created_at)
    if collection.created_at == created_at:
        publish(Events.CREATE_COLLECTION,
                actor_id=role.id,
                params={'collection': collection})
    db.session.commit()
    Authz.flush()
    refresh_collection(collection.id)
    return index.index_collection(collection, sync=sync)
Exemple #27
0
def create_code():
    data = parse_request(RoleCodeCreateSchema)
    signature = Role.SIGNATURE.dumps(data['email'])
    url = '{}activate/{}'.format(app_ui_url, signature)
    role = Role(email=data['email'], name='Visitor')
    notify_role_template(role, 'Registration',
                         'email/registration_code.html',
                         url=url)
    return jsonify({
        'status': 'ok',
        'message': 'To proceed, please check your email.'
    })
Exemple #28
0
def load_role():
    request.auth_roles = set([Role.system(Role.SYSTEM_GUEST)])
    request.auth_role = None
    request.logged_in = False

    if session.get('user'):
        request.auth_roles.update(session.get('roles', []))
        request.auth_role = Role.by_id(session.get('user'))
        request.logged_in = True
    else:
        api_key = request.args.get('api_key')
        if api_key is None:
            auth_header = request.headers.get('Authorization') or ''
            if auth_header.lower().startswith('apikey'):
                api_key = auth_header.split(' ', 1).pop()
        role = Role.by_api_key(api_key)
        if role is None:
            return
        request.auth_role = role
        request.auth_roles.update([Role.system(Role.SYSTEM_USER), role.id])
        request.logged_in = True
Exemple #29
0
def load_role():
    request.auth_roles = set([Role.system(Role.SYSTEM_GUEST)])
    request.auth_role = None
    request.logged_in = False

    auth_header = request.headers.get('Authorization')

    if session.get('user'):
        request.auth_roles.update(session.get('roles', []))
        request.auth_role = Role.by_id(session.get('user'))
        request.logged_in = True
    elif auth_header is not None:
        if not auth_header.lower().startswith('apikey'):
            return
        api_key = auth_header.split(' ', 1).pop()
        role = Role.by_api_key(api_key)
        if role is None:
            return
        request.auth_role = role
        request.auth_roles.update([Role.system(Role.SYSTEM_USER), role.id])
        request.logged_in = True
Exemple #30
0
def create_collection(data, role=None, sync=False):
    role = role or Role.load_cli_user()
    created_at = datetime.utcnow()
    collection = Collection.create(data, creator=role, created_at=created_at)
    if collection.created_at == created_at:
        publish(Events.CREATE_COLLECTION,
                actor_id=role.id,
                params={'collection': collection})
    db.session.commit()
    Authz.flush()
    refresh_collection(collection.id)
    return index.index_collection(collection, sync=sync)
Exemple #31
0
def _get_credential_authz(credential):
    if credential is None or not len(credential):
        return
    if ' ' in credential:
        mechanism, credential = credential.split(' ', 1)
    authz = Authz.from_token(credential, scope=request.path)
    if authz is not None:
        return authz

    role = Role.by_api_key(credential)
    if role is not None:
        return Authz.from_role(role=role)
Exemple #32
0
 def create_user(self,
                 foreign_id='tester',
                 name=None,
                 email=None,
                 is_admin=False):
     role = Role.load_or_create(foreign_id,
                                Role.USER,
                                name or foreign_id,
                                email=email or self.fake.email(),
                                is_admin=is_admin)
     db.session.commit()
     return role
Exemple #33
0
def ingest_complete(collection, role_id=None):
    """Operations supposed to be performed when an ingest process completes."""
    from aleph.logic.collections import update_collection, collection_url  # noqa
    update_collection(collection)
    role = Role.by_id(role_id)
    if role is not None:
        # notify the user that their import is completed.
        notify_role_template(role,
                             collection.label,
                             'email/ingest.html',
                             collection=collection,
                             url=collection_url(collection.id))
Exemple #34
0
def get_role(role_id):
    if role_id is None:
        return
    key = cache.object_key(Role, role_id)
    data = cache.get_complex(key)
    if data is None:
        role = Role.by_id(role_id)
        if role is None:
            return
        data = role.to_dict()
        cache.set_complex(key, data, expires=cache.EXPIRE)
    return data
Exemple #35
0
def crawldir(path, language=None, foreign_id=None):
    """Crawl the given directory."""
    path = Path(path)
    if foreign_id is None:
        foreign_id = 'directory:%s' % slugify(path)
    authz = Authz.from_role(Role.load_cli_user())
    config = {'foreign_id': foreign_id, 'label': path.name, 'casefile': False}
    create_collection(config, authz)
    collection = Collection.by_foreign_id(foreign_id)
    log.info('Crawling %s to %s (%s)...', path, foreign_id, collection.id)
    crawl_directory(collection, path)
    log.info('Complete. Make sure a worker is running :)')
Exemple #36
0
def handle_facebook_oauth(sender, provider=None, oauth=None):
    from aleph.model import Role
    if 'facebook.com' not in provider.base_url:
        return

    token = (oauth.get('access_token'), '')
    me = provider.get('me?fields=id,name,email', token=token)
    user_id = 'facebook:%s' % me.data.get('id')
    return Role.load_or_create(user_id,
                               Role.USER,
                               me.data.get('name'),
                               email=me.data.get('email'))
Exemple #37
0
def handle_google_oauth(sender, provider=None, oauth=None):
    from aleph.model import Role
    if 'googleapis.com' not in provider.base_url:
        return

    token = (oauth.get('access_token'), '')
    me = provider.get('userinfo', token=token)
    user_id = 'google:%s' % me.data.get('id')
    return Role.load_or_create(user_id,
                               Role.USER,
                               me.data.get('name'),
                               email=me.data.get('email'))
Exemple #38
0
def _get_credential_authz(credential):
    if credential is None or not len(credential):
        return
    if ' ' in credential:
        mechanism, credential = credential.split(' ', 1)
    authz = Authz.from_token(credential, scope=request.path)
    if authz is not None:
        return authz

    role = Role.by_api_key(credential)
    if role is not None:
        return Authz.from_role(role=role)
Exemple #39
0
def ooemail_register():
    # XXX need some validation here, yesyes;
    user = Role.create_by_email(
        email=request.args.get('email'),
        pw=request.args.get('pw'),
        mailing_list=request.args.get('mailing_list'),
    )
    # XXX re-implement welcome mail
    #alerts.mail_welcome_email(user)
    # XXX isolate flask-login
    store_login(user)
    return 'created oo email'
Exemple #40
0
 def load_fixtures(self):
     self.private_coll = Collection.create({
         'foreign_id': 'test_private',
         'label': "Private Collection",
         'category': 'grey'
     })
     self._banana = Entity.create(
         {
             'schema': 'Person',
             'properties': {
                 'name': ['Banana'],
             }
         }, self.private_coll)
     user = Role.by_foreign_id(Role.SYSTEM_USER)
     Permission.grant(self.private_coll, user, True, False)
     self.public_coll = Collection.create({
         'foreign_id': 'test_public',
         'label': "Public Collection",
         'category': 'news'
     })
     self._kwazulu = Entity.create(
         {
             'schema': 'Company',
             'properties': {
                 'name': ['KwaZulu'],
                 'alias': ['kwazulu']
             }
         }, self.public_coll)
     visitor = Role.by_foreign_id(Role.SYSTEM_GUEST)
     Permission.grant(self.public_coll, visitor, True, False)
     db.session.commit()
     drop_aggregator(self.public_coll)
     stage = get_stage(self.private_coll, OP_PROCESS)
     process_collection(stage, self.public_coll, ingest=False, sync=True)
     stage = get_stage(self.private_coll, OP_INDEX)
     samples = read_entities(self.get_fixture_path('samples.ijson'))
     drop_aggregator(self.private_coll)
     index_entities(stage, self.private_coll, samples, sync=True)
     stage = get_stage(self.private_coll, OP_PROCESS)
     process_collection(stage, self.private_coll, ingest=False, sync=True)
Exemple #41
0
def metadata():
    """Get operational metadata for the frontend.
    ---
    get:
      summary: Retrieve system metadata from the application.
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
      tags:
      - System
    """
    locale = get_locale()
    auth = {}
    if settings.PASSWORD_LOGIN:
        auth['password_login_uri'] = url_for('sessions_api.password_login')
        auth['registration_uri'] = url_for('roles_api.create_code')
    if settings.OAUTH:
        auth['oauth_uri'] = url_for('sessions_api.oauth_init')

    locales = settings.UI_LANGUAGES
    locales = {l: Locale(l).get_language_name(l) for l in locales}

    data = {
        'status': 'ok',
        'maintenance': request.authz.in_maintenance,
        'app': {
            'title': settings.APP_TITLE,
            'description': settings.APP_DESCRIPTION,
            'version': __version__,
            'banner': settings.APP_BANNER,
            'ui_uri': settings.APP_UI_URL,
            'samples': settings.SAMPLE_SEARCHES,
            'logo': settings.APP_LOGO,
            'favicon': settings.APP_FAVICON,
            'locale': str(locale),
            'locales': locales
        },
        'categories': Collection.CATEGORIES,
        'model': model,
        'token': None,
        'auth': auth
    }

    if settings.SINGLE_USER:
        role = Role.load_cli_user()
        authz = Authz.from_role(role)
        data['token'] = authz.to_token(role=role)
    return jsonify(data)
Exemple #42
0
def handle_google_oauth(sender, provider=None, session=None):
    # If you wish to use another OAuth provider with your installation of
    # aleph, you can create a Python extension package and include a
    # custom oauth handler like this, which will create roles and state
    # for your session.
    if 'googleapis.com' not in provider.base_url:
        return
    me = provider.get('userinfo')
    user_id = 'google:%s' % me.data.get('id')
    role = Role.load_or_create(user_id, Role.USER, me.data.get('name'),
                               email=me.data.get('email'))
    session['roles'].append(role.id)
    session['user'] = role.id
Exemple #43
0
def createuser(foreign_id, password=None, name=None, email=None,
               is_admin=False):
    """Create a user and show their API key."""
    role = Role.load_or_create(foreign_id, Role.USER,
                               name or foreign_id,
                               email=email or "*****@*****.**",
                               is_admin=is_admin)
    if password is not None:
        role.set_password(password)
    db.session.add(role)
    db.session.commit()
    update_role(role)
    return role.api_key
Exemple #44
0
def permissions_update(collection):
    authz.require(authz.collection_write(collection))
    data = request_data()
    validate(data, 'permission.json#')

    role = Role.all().filter(Role.id == data['role']).first()
    if role is None:
        raise BadRequest()

    permission = Permission.grant_collection(collection.id, role, data['read'],
                                             data['write'])
    db.session.commit()
    return jsonify({'status': 'ok', 'updated': permission})
Exemple #45
0
    def test_authenticate_using_ldap_with_bad_user_pass(self):
        secret = self.fake.password()
        email = self.fake.email()
        fake_ldap_conn = flexmock(set_option=lambda x, y: x)

        (flexmock(fake_ldap_conn).should_receive('simple_bind_s').with_args(
            get_config('LDAP_BASE_DN').format(email),
            secret).and_raise(LDAPException('Failed auth.')).times(1))

        (flexmock(ldap).should_receive('initialize').and_return(fake_ldap_conn)
         )

        self.assertIsNone(Role.authenticate_using_ldap(email, secret))
Exemple #46
0
def create_collection(foreign_id, data, role=None):
    role = role or Role.load_cli_user()
    collection = Collection.by_foreign_id(foreign_id)
    if collection is None:
        data['foreign_id'] = foreign_id
        collection = Collection.create(data, role=role)
    else:
        languages = ensure_list(data.get('languages'))
        if len(languages):
            collection.languages = languages
    db.session.commit()
    index.index_collection(collection)
    return collection
Exemple #47
0
def challenge_role(data):
    """Given an email address, this will send out a message to allow
    the user to then register an account."""
    signature = Role.SIGNATURE.dumps(data["email"])
    url = "{}activate/{}".format(settings.APP_UI_URL, signature)
    role = Role(email=data["email"], name=data["email"])
    params = dict(
        url=url, role=role, ui_url=settings.APP_UI_URL, app_title=settings.APP_TITLE
    )
    plain = render_template("email/registration_code.txt", **params)
    html = render_template("email/registration_code.html", **params)
    log.info("Challenge: %s", plain)
    email_role(role, gettext("Registration"), html=html, plain=plain)
Exemple #48
0
def get_role(role_id):
    if role_id is None:
        return
    key = cache.object_key(Role, role_id)
    data = cache.get_complex(key)
    if data is None:
        log.debug("Role [%s]: object cache miss", role_id)
        role = Role.by_id(role_id)
        if role is None:
            return
        data = role.to_dict()
        cache.set_complex(key, data, expire=cache.EXPIRE)
    return data
Exemple #49
0
def callback():
    resp = oauth_provider.authorized_response()
    if resp is None or isinstance(resp, OAuthException):
        log.warning("Failed OAuth: %r", resp)
        # FIXME: notify the user, somehow.
        return redirect('/')

    session['oauth'] = resp
    session['roles'] = [Role.system(Role.SYSTEM_USER)]
    signals.handle_oauth_session.send(provider=oauth_provider, session=session)
    db.session.commit()
    log.info("Logged in: %r", session['user'])
    return redirect('/')
Exemple #50
0
def permissions_update(collection):
    authz.require(authz.collection_write(collection))
    data = request_data()
    validate(data, "permission.json#")

    role = Role.all().filter(Role.id == data["role"]).first()
    if role is None:
        raise BadRequest()

    permission = Permission.grant_collection(collection, role, data["read"], data["write"])
    db.session.commit()
    log_event(request)
    return jsonify({"status": "ok", "updated": permission})
Exemple #51
0
def create():
    data = request_data()
    email = data.get('email')
    name = data.get('name') or email
    password = data.get('password')
    signature = data.get('code')

    if not email or not password or not signature:
        abort(400)

    try:
        # Make sure registration is allowed
        assert get_config('PASSWORD_REGISTRATION')

        # Make sure password is set and not too short
        assert len(password) >= Role.PASSWORD_MIN_LENGTH

        # Make sure the signature is valid
        assert email == Role.SIGNATURE_SERIALIZER.loads(
            signature, salt=email, max_age=Role.SIGNATURE_MAX_AGE)
    except:
        abort(400)

    role = Role.by_email(email).first()

    if role:
        return jsonify(dict(status='ok')), 200

    role = Role.load_or_create(foreign_id='password:{}'.format(email),
                               type=Role.USER,
                               name=name,
                               email=email)
    role.set_password(password)

    db.session.add(role)
    db.session.commit()

    return jsonify(dict(status='ok')), 201
Exemple #52
0
def suggest():
    request.authz.require(request.authz.logged_in)
    prefix = stringify(request.args.get('prefix'))
    if prefix is None or len(prefix) < 3:
        # Do not return 400 because it's a routine event.
        return jsonify({
            'status': 'error',
            'message': 'prefix filter is too short',
            'results': [],
            'total': 0
        })
    # this only returns users, not groups
    q = Role.by_prefix(prefix)
    return jsonify(Pager(q, limit=10))
Exemple #53
0
def permissions_update(collection):
    request.authz.require(request.authz.collection_write(collection))
    data = request_data()
    validate(data, 'permission.json#')

    role = Role.all().filter(Role.id == data['role_id']).first()
    collection = Collection.by_id(collection)
    if role is None or collection is None:
        raise BadRequest()
    request.authz.require(check_visible(role))

    perm = update_permission(role, collection, data['read'], data['write'])
    log_event(request)
    return jsonify({'status': 'ok', 'updated': perm})
Exemple #54
0
def create_code():
    data = parse_request(RoleCodeCreateSchema)
    signature = Role.SIGNATURE.dumps(data['email'])
    url = '{}activate/{}'.format(settings.APP_UI_URL, signature)
    role = Role(email=data['email'], name='Visitor')
    log.info("Confirmation URL [%r]: %s", role, url)
    notify_role(role,
                gettext('Registration'),
                'email/registration_code.html',
                url=url)
    return jsonify({
        'status': 'ok',
        'message': gettext('To proceed, please check your email.')
    })
Exemple #55
0
def password_login():
    """Provides email and password authentication."""
    data = parse_request(LoginSchema)
    q = Role.by_email(data.get('email'))
    q = q.filter(Role.password_digest != None)  # noqa
    role = q.first()

    if role is None:
        return Unauthorized("Authentication has failed.")

    if not role.check_password(data.get('password')):
        return Unauthorized("Authentication has failed.")

    return jsonify({'status': 'ok', 'token': create_token(role)})
Exemple #56
0
def complete_export(export_id, file_path=None):
    export = Export.by_id(export_id)
    if file_path:
        export.set_filepath(file_path)
    export.publish()
    db.session.commit()
    params = {"export": export}
    role = Role.by_id(export.creator_id)
    publish(
        Events.COMPLETE_EXPORT,
        params=params,
        channels=[role],
    )
    send_export_notification(export)
Exemple #57
0
def create():
    """Create a user role.
    ---
    post:
      summary: Create a user account
      description: >
        Create a user role by supplying the required account details.
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RoleCreate'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Role'
      tags:
      - Role
    """
    require(settings.PASSWORD_LOGIN)
    require(not request.authz.in_maintenance)
    data = parse_request("RoleCreate")
    try:
        email = Role.SIGNATURE.loads(data.get("code"),
                                     max_age=Role.SIGNATURE_MAX_AGE)
    except BadSignature:
        return jsonify({
            "status": "error",
            "message": gettext("Invalid code")
        },
                       status=400)

    role = Role.by_email(email)
    if role is not None:
        return jsonify(
            {
                "status": "error",
                "message": gettext("Email is already registered")
            },
            status=409,
        )

    role = create_user(email, data.get("name"), data.get("password"))
    # Let the serializer return more info about this user
    request.authz = Authz.from_role(role)
    tag_request(role_id=role.id)
    return RoleSerializer.jsonify(role, status=201)
Exemple #58
0
def create_user(email, name, password, is_admin=False):
    """Create a password-based user."""
    foreign_id = 'password:{}'.format(email)
    role = Role.load_or_create(foreign_id,
                               Role.USER,
                               name,
                               email=email,
                               is_admin=is_admin)
    if password is not None:
        role.set_password(password)
    db.session.add(role)
    db.session.commit()
    update_role(role)
    return role