Esempio n. 1
0
 def _process(self):
     quiet = request.form.get('quiet') == '1'
     force = request.form.get('force') == '1'
     persistent = request.form.get('persistent') == '1' and api_settings.get('allow_persistent')
     old_key = self.user.api_key
     if old_key:
         if not force:
             raise BadRequest('There is already an API key for this user')
         if old_key.is_blocked and not session.user.is_admin:
             raise Forbidden
         old_key.is_active = False
         db.session.flush()
     key = APIKey(user=self.user)
     db.session.add(key)
     if persistent:
         key.is_persistent_allowed = persistent
     elif old_key:
         key.is_persistent_allowed = old_key.is_persistent_allowed
     if not quiet:
         if old_key:
             flash(_('Your API key has been successfully replaced.'), 'success')
             if old_key.use_count:
                 flash(_('Please update any applications which use old key.'), 'warning')
         else:
             flash(_('Your API key has been successfully created.'), 'success')
     db.session.flush()
     return redirect_or_jsonify(url_for('api.user_profile'), flash=not quiet,
                                is_persistent_allowed=key.is_persistent_allowed)
Esempio n. 2
0
 def _process(self):
     quiet = request.form.get('quiet') == '1'
     force = request.form.get('force') == '1'
     persistent = request.form.get(
         'persistent') == '1' and api_settings.get('allow_persistent')
     old_key = self.user.api_key
     if old_key:
         if not force:
             raise BadRequest('There is already an API key for this user')
         if old_key.is_blocked and not session.user.is_admin:
             raise Forbidden
         old_key.is_active = False
         db.session.flush()
     key = APIKey(user=self.user)
     db.session.add(key)
     if persistent:
         key.is_persistent_allowed = persistent
     elif old_key:
         key.is_persistent_allowed = old_key.is_persistent_allowed
     if not quiet:
         if old_key:
             flash(_('Your API key has been successfully replaced.'),
                   'success')
             if old_key.use_count:
                 flash(
                     _('Please update any applications which use old key.'),
                     'warning')
         else:
             flash(_('Your API key has been successfully created.'),
                   'success')
     db.session.flush()
     return redirect_or_jsonify(
         url_for('api.user_profile'),
         flash=not quiet,
         is_persistent_allowed=key.is_persistent_allowed)
Esempio n. 3
0
def checkAK(apiKey, signature, timestamp, path, query):
    apiMode = api_settings.get('security_mode')
    if not apiKey:
        if apiMode in {
                APIMode.ONLYKEY, APIMode.ONLYKEY_SIGNED, APIMode.ALL_SIGNED
        }:
            raise HTTPAPIError('API key is missing', 403)
        return None, True
    try:
        UUID(hex=apiKey)
    except ValueError:
        raise HTTPAPIError('Malformed API key', 400)
    ak = APIKey.find_first(token=apiKey, is_active=True)
    if not ak:
        raise HTTPAPIError('Invalid API key', 403)
    if ak.is_blocked:
        raise HTTPAPIError('API key is blocked', 403)
    # Signature validation
    onlyPublic = False
    if signature:
        validateSignature(ak, signature, timestamp, path, query)
    elif apiMode == APIMode.ALL_SIGNED:
        raise HTTPAPIError('Signature missing', 403)
    elif apiMode in {APIMode.SIGNED, APIMode.ONLYKEY_SIGNED}:
        onlyPublic = True
    return ak, onlyPublic
Esempio n. 4
0
 def _process(self):
     form = AdminSettingsForm(obj=FormDefaults(**api_settings.get_all()))
     if form.validate_on_submit():
         api_settings.set_multi(form.data)
         flash(_('Settings saved'), 'success')
         return redirect(url_for('.admin_settings'))
     count = APIKey.find(is_active=True).count()
     return WPAPIAdmin.render_template('admin_settings.html', form=form, count=count)
Esempio n. 5
0
 def _process(self):
     form = AdminSettingsForm(obj=FormDefaults(**api_settings.get_all()))
     if form.validate_on_submit():
         api_settings.set_multi(form.data)
         flash(_('Settings saved'), 'success')
         return redirect(url_for('.admin_settings'))
     count = APIKey.find(is_active=True).count()
     return WPAPIAdmin.render_template('admin_settings.html', form=form, count=count)
Esempio n. 6
0
def _merge_users(target, source, **kwargs):
    # Get the current active API keys
    ak_user = target.api_key
    ak_merged = source.api_key
    # Move all inactive keys to the new user
    APIKey.find(user_id=source.id, is_active=False).update({'user_id': target.id})
    if ak_merged and not ak_user:
        ak_merged.user = target
    elif ak_user and ak_merged:
        # Both have a key, keep the main one unless it's unused and the merged one isn't.
        if ak_user.use_count or not ak_merged.use_count:
            ak_merged.is_active = False
            ak_merged.user = target
        else:
            ak_user.is_active = False
            db.session.flush()  # flush the deactivation so we can reassociate the user
            ak_merged.user = target
Esempio n. 7
0
def _merge_users(target, source, **kwargs):
    # Get the current active API keys
    ak_user = target.api_key
    ak_merged = source.api_key
    # Move all inactive keys to the new user
    APIKey.find(user_id=source.id, is_active=False).update({'user_id': target.id})
    if ak_merged and not ak_user:
        ak_merged.user = target
    elif ak_user and ak_merged:
        # Both have a key, keep the main one unless it's unused and the merged one isn't.
        if ak_user.use_count or not ak_merged.use_count:
            ak_merged.is_active = False
            ak_merged.user = target
        else:
            ak_user.is_active = False
            db.session.flush()  # flush the deactivation so we can reassociate the user
            ak_merged.user = target
Esempio n. 8
0
def checkAK(apiKey, signature, timestamp, path, query):
    apiMode = api_settings.get('security_mode')
    if not apiKey:
        if apiMode in {APIMode.ONLYKEY, APIMode.ONLYKEY_SIGNED, APIMode.ALL_SIGNED}:
            raise HTTPAPIError('API key is missing', 403)
        return None, True
    try:
        UUID(hex=apiKey)
    except ValueError:
        raise HTTPAPIError('Malformed API key', 400)
    ak = APIKey.find_first(token=apiKey, is_active=True)
    if not ak:
        raise HTTPAPIError('Invalid API key', 403)
    if ak.is_blocked:
        raise HTTPAPIError('API key is blocked', 403)
    # Signature validation
    onlyPublic = False
    if signature:
        validateSignature(ak, signature, timestamp, path, query)
    elif apiMode == APIMode.ALL_SIGNED:
        raise HTTPAPIError('Signature missing', 403)
    elif apiMode in {APIMode.SIGNED, APIMode.ONLYKEY_SIGNED}:
        onlyPublic = True
    return ak, onlyPublic
Esempio n. 9
0
 def _process(self):
     keys = sorted(APIKey.find_all(is_active=True), key=lambda ak: (ak.use_count == 0, ak.user.full_name))
     return WPAPIAdmin.render_template('admin_keys.html', keys=keys)
Esempio n. 10
0
 def _process(self):
     keys = sorted(APIKey.find_all(is_active=True),
                   key=lambda ak: (ak.use_count == 0, ak.user.full_name))
     return WPAPIAdmin.render_template('admin_keys.html', 'api', keys=keys)
Esempio n. 11
0
 def has_data(self):
     return bool(APIKey.find().count())
Esempio n. 12
0
    def migrate_keys(self):
        print cformat('%{white!}migrating api keys')
        for idx_key, ak in committing_iterator(
                self.zodb_root['apikeys'].iteritems()):
            if idx_key != ak._key:
                print cformat(
                    '%{red!}!!!%{reset} '
                    '%{yellow!}Skipping {} - index key {} does not match'
                ).format(ak._key, idx_key)
                continue
            elif str(ak._user.id) not in self.zodb_root['avatars']:
                print cformat(
                    '%{red!}!!!%{reset} '
                    '%{yellow!}Skipping {} - user {} does not exist').format(
                        ak._key, ak._user.id)
                continue
            elif ak._user.apiKey != ak:
                print cformat(
                    '%{red!}!!!%{reset} '
                    '%{yellow!}Skipping {} - user {} has a different api key set'
                ).format(ak._key, ak._user.id)
                continue

            last_used_uri = None
            if ak._lastPath and ak._lastQuery:
                last_used_uri = '{}?{}'.format(
                    convert_to_unicode(ak._lastPath),
                    convert_to_unicode(ak._lastQuery))
            elif ak._lastPath:
                last_used_uri = convert_to_unicode(ak._lastPath)

            api_key = APIKey(token=ak._key,
                             secret=ak._signKey,
                             user_id=ak._user.id,
                             is_blocked=ak._isBlocked,
                             is_persistent_allowed=getattr(
                                 ak, '_persistentAllowed', False),
                             created_dt=self._to_utc(ak._createdDT),
                             last_used_dt=self._to_utc(ak._lastUsedDT),
                             last_used_ip=ak._lastUsedIP,
                             last_used_uri=last_used_uri,
                             last_used_auth=ak._lastUseAuthenticated,
                             use_count=ak._useCount)
            db.session.add(api_key)
            print cformat(
                '%{green}+++%{reset} %{cyan}{}%{reset} [%{blue!}{}%{reset}]'
            ).format(ak._key, ak._user.email)

            for old_key in ak._oldKeys:
                # We have no creation time so we use *something* older..
                fake_created_dt = self._to_utc(
                    ak._createdDT) - timedelta(hours=1)
                # We don't have anything besides the api key for old keys, so we use a random secret
                old_api_key = APIKey(token=old_key,
                                     secret=unicode(uuid4()),
                                     user_id=ak._user.id,
                                     created_dt=fake_created_dt,
                                     is_active=False)
                db.session.add(old_api_key)
                print cformat(
                    '%{blue!}***%{reset} %{cyan}{}%{reset} [%{yellow}old%{reset}]'
                ).format(old_key)

            db.session.flush()
Esempio n. 13
0
 def has_data(self):
     return bool(APIKey.find().count())