Пример #1
0
def system_pages(name):
    if current_user.is_authenticated and name:
        args = getattr(interface, name)()
        combine_dicts(args, {"authKey": current_user.get_auth_token()})
        return render_template("pages/" + name + "/index.html", **args)
    else:
        return {"status": "Could Not Log In."}
Пример #2
0
 def get(self, **kwargs):
     """
     Get authentication token
     """
     token = current_user.get_auth_token()
     return dict(username=current_user.username,
                 value=token, role=current_user.role)
Пример #3
0
def loginPage():
    if current_user.is_authenticated:

        args = {"apps": config.getApps(), "authKey":current_user.get_auth_token(), "currentUser":current_user.email}
        return render_template("container.html", **args)
    else:
        return {"status" : "Could Not Log In."}
Пример #4
0
def get_auth_token_cached(current_user):
    """ Cache users tokens. If token is less then 15 min away from expiry, expired or
    not in cache, generate a fresh auth token.

    # todo
    Note: This method is a hack. Replace it with encrypted, auto-expiring redis cache
    as soon as the redis cluster is deployed.

    Faults:
     - will only work if user is served from precisely this server && instance
     - will cause memory leaks if not pruned every once in a while
    """
    global auth_token_cache

    if not current_user or not current_user.is_authenticated:
        return

    def _has_expired(dto: dt.datetime) -> bool:
        return dto < dt.datetime.now()

    cache = auth_token_cache.get(current_user.id)
    if (cache and _has_expired(cache[1])) or not cache:
        expiry_time = dt.datetime.now() + dt.timedelta(
            seconds=(app.config['SECURITY_TOKEN_MAX_AGE'] - 900))
        auth_token_cache[current_user.id] = \
            (current_user.get_auth_token(), expiry_time)

    return auth_token_cache[current_user.id][0]
Пример #5
0
 def __func():
     if current_user.is_authenticated:
         return json.dumps({"auth_token":
                            current_user.get_auth_token()}), SUCCESS
     else:
         current_app.logger.debug('Unsuccessful login attempt')
         return {"error": "Could not log in."}, UNAUTHORIZED_ERROR
Пример #6
0
 def get(self):
     return {
         'user': {
             'username': current_user.username,
             'email': current_user.email,
             'authtoken': current_user.get_auth_token(),
         }
     }
Пример #7
0
 def post(self, **kwargs):
     """
     Get authentication token
     It's the same as the GET request,
     but supports authenticating via saml-response in the body
     """
     token = current_user.get_auth_token()
     return dict(value=token, role=current_user.role)
Пример #8
0
def user():
    """ Info on the currently logged in user. """
    if current_user.is_anonymous():
        raise ApiException(401, "not authenticated")

    user = serializers.to_dict(current_user)
    user['authentication_token'] = current_user.get_auth_token()

    return send_api_response({'current_user': user})
Пример #9
0
 def post(self, **kwargs):
     """
     Get authentication token
     It's the same as the GET request,
     but supports authenticating via saml-response in the body
     """
     token = current_user.get_auth_token()
     return dict(username=current_user.username,
                 value=token, role=current_user.role)
Пример #10
0
 def __func():
     if current_user.is_authenticated and interface_name:
         args = getattr(interface, interface_name)()
         combine_dicts(args, {"authKey": current_user.get_auth_token()})
         return render_template("pages/" + interface_name + "/index.html",
                                **args), SUCCESS
     else:
         current_app.logger.debug('Unsuccessful login attempt')
         return {"error": "Could not Log In."}, UNAUTHORIZED_ERROR
Пример #11
0
def _execute_task(task_queue, execution_id, execution_parameters, context):
    context['rest_token'] = current_user.get_auth_token()
    context['tenant_name'] = current_app.config[CURRENT_TENANT_CONFIG].name
    execution_parameters['__cloudify_context'] = context
    celery = celery_client.get_client()
    try:
        return celery.execute_task(task_queue=task_queue,
                                   task_id=execution_id,
                                   kwargs=execution_parameters)
    finally:
        celery.close()
Пример #12
0
Файл: ui.py Проект: fanlens/web
def _hand_off_to_app(path: str) -> Response:
    return render_template(
        'ui.html',
        bot_id=_CONFIG.get("BOT", "client_id"),
        jwt=create_jwt_for_user(
            current_user if current_user.has_role('tagger') else g.demo_user),
        auth_token=(current_user.get_auth_token()
                    if current_user.has_role('tagger') else
                    g.demo_user.get_auth_token()),
        path=path,
        version=_CONFIG.get('DEFAULT', 'version'))
Пример #13
0
def _execute_task(execution_id, execution_parameters, context):
    context['rest_token'] = current_user.get_auth_token()
    context['tenant'] = _get_tenant_dict()
    context['task_target'] = MGMTWORKER_QUEUE
    execution_parameters['__cloudify_context'] = context
    celery = celery_client.get_client()
    try:
        return celery.execute_task(task_queue=MGMTWORKER_QUEUE,
                                   task_id=execution_id,
                                   kwargs=execution_parameters)
    finally:
        celery.close()
Пример #14
0
def default():
    if current_user.is_authenticated:
        default_page_name = "dashboard"
        args = {
            "apps": config.getApps(),
            "authKey": current_user.get_auth_token(),
            "currentUser": current_user.email,
            "default_page": default_page_name
        }
        return render_template("container.html", **args)
    else:
        return {"status": "Could Not Log In."}
Пример #15
0
def default():
    if current_user.is_authenticated:
        default_page_name = 'dashboard'
        args = {
            "apps": running_context.get_apps(),
            "authKey": current_user.get_auth_token(),
            "currentUser": current_user.email,
            "default_page": default_page_name
        }
        return render_template("container.html", **args)
    else:
        return redirect(url_for('/login'))
Пример #16
0
def cancel_execution(execution_id):
    message = {
        'service_task': {
            'task_name': 'cancel-workflow',
            'kwargs': {
                'execution_id': execution_id,
                'rest_token': current_user.get_auth_token(),
                'tenant': _get_tenant_dict()
            }
        }
    }
    _send_mgmtworker_task(message, routing_key='service')
def cancel_execution(execution_id):
    message = {
        'service_task': {
            'task_name': 'cancel-workflow',
            'kwargs': {
                'execution_id': execution_id,
                'rest_token': current_user.get_auth_token(),
                'tenant': _get_tenant_dict(),
                'execution_token': generate_execution_token(execution_id)
            }
        }
    }
    _send_mgmtworker_task(message, routing_key='service')
Пример #18
0
def _execute_task(execution_id, execution_parameters, context):
    context['rest_token'] = current_user.get_auth_token()
    context['tenant'] = _get_tenant_dict()
    context['task_target'] = MGMTWORKER_QUEUE
    execution_parameters['__cloudify_context'] = context
    message = {
        'cloudify_task': {
            'kwargs': execution_parameters
        },
        'id': execution_id,
    }

    _send_mgmtworker_task(message)
Пример #19
0
def cancel_execution(execution):
    sm = get_storage_manager()
    managers = sm.list(models.Manager)
    message = {
        'service_task': {
            'task_name': 'cancel-workflow',
            'kwargs': {
                'rest_host': [manager.private_ip for manager in managers],
                'execution_id': execution.id,
                'rest_token': current_user.get_auth_token(),
                'tenant': _get_tenant_dict(),
                'execution_token': generate_execution_token(execution)
            }
        }
    }
    _broadcast_mgmtworker_task(message)
Пример #20
0
 def get_user() -> str:
     """
     Get a JSON-fied user object including a JWT to be used for api endpoints.
     The user needs to have a proper auth token / login session in order to exchange it for a JWT that can be used
     in a non session context.
     :return: the JSON-fied user object.
     """
     user = (current_user
             if current_user.has_role('tagger') else g.demo_user)
     user_json: str = jsonify(email=user.email,
                              active=user.active,
                              confirmed_at=user.confirmed_at,
                              auth_token=current_user.get_auth_token(),
                              jwt=create_jwt_for_user(current_user),
                              roles=[role.name for role in user.roles])
     return user_json
Пример #21
0
def get_device_list():
    auth_token = current_user.get_auth_token()
    if auth_token:
        baseURL = request.base_url.replace(request.path, "")
        device_list_req = requests.post(baseURL + "/configuration/LinuxShell/devices/all", headers={"Authentication-Token":auth_token}, verify=False)
        if device_list_req.status_code == 200:
            device_list = device_list_req.json()
            device_list_parsed = []

            if "status" not in device_list:
                for device in device_list:
                    device_list_parsed.append((device['name'],device['ip'],device['port'],device['username']))
            return device_list_parsed
        else:
            return "Could not retrieve devices"
    else:
        return "Current user not logged in"
Пример #22
0
def _get_plugin_message(plugin, task='install-plugin', target_names=None):
    """Make plugin-related service task message.

    This is for creating plugin install/uninstall messages, to send to
    the mgmtworkers/agents.
    """
    sm = get_storage_manager()
    managers = sm.list(models.Manager)
    message = {
        'service_task': {
            'task_name': task,
            'kwargs': {
                'plugin': plugin.to_dict(),
                'rest_host': [manager.private_ip for manager in managers],
                'rest_token': current_user.get_auth_token(),
                'tenant': _get_tenant_dict(),
            }
        }
    }
    if target_names:
        message['service_task']['kwargs']['target'] = target_names
    return message
Пример #23
0
def loginInfo():
    print current_user
    if current_user.is_authenticated:
        return json.dumps({"auth_token" : current_user.get_auth_token()})
    else:
        return {"status" : "Could Not Log In."}
Пример #24
0
def token():
    token = current_user.get_auth_token()
    return render_template('security/show_token.html', token=token)
Пример #25
0
 def get(self):
     return {'token': current_user.get_auth_token()}
Пример #26
0
def auth_token():
    return jsonify({'auth_token': current_user.get_auth_token()})
Пример #27
0
def loginInfo():
    if current_user.is_authenticated:
        return json.dumps({"auth_token" : current_user.get_auth_token()})
    else:
        return {"status" : "Could Not Log In."}
Пример #28
0
def load_from_api(resource_name, resource_id=None, page=None, return_everything=False, fields=None, params=None, pagesize=None):
    """ Load data from the PMG API.

    :param str resource_name: resource to load (used as the start of the URL), or a full URL
    :param int resource_id: resource id (optional), appended to the resource name
    :param int page: page number to load (default is the first page)
    :param bool return_everything: fetch all pages? (default: False)
    :param list fields: list of field names to ask for (V2 only).
    :param dict params: additional query params
    :param int pagesize: items per page
    """
    params = {} if (params is None) else params
    # check for full URL?
    if resource_name.startswith('http'):
        resource_name = resource_name.split('/', 3)[3]

    v2 = resource_name.startswith('v2')
    if fields and not v2:
        raise ValueError("Fields parameter is only supported for API v2 urls.")

    query_str = resource_name
    if resource_id:
        query_str += "/" + str(resource_id)
    if not v2:
        query_str += '/'

    if page:
        params["page"] = str(page)
    if fields:
        params["fields"] = ','.join(fields)
    if pagesize:
        params["per_page"] = pagesize

    headers = {}
    # add auth header
    if current_user.is_authenticated():
        headers = {'Authentication-Token': current_user.get_auth_token()}

    try:
        response = http.request('GET', API_URL + query_str, headers=headers, fields=params)

        if response.status == 404:
            abort(404)

        if response.status != 200 and response.status not in [401, 403]:
            try:
                msg = response_json(response).get('message')
            except Exception:
                msg = None

            raise ApiException(response.status, msg or "An unspecified error has occurred.")

        out = response_json(response)
        if return_everything:
            next_response_json = out
            i = 0
            while next_response_json.get('next') and i < 1000:
                next_response = http.request('GET', next_response_json.get('next'), headers=headers)
                next_response_json = response_json(next_response)
                out['results'] += next_response_json['results']
                i += 1
            if out.get('next'):
                out.pop('next')

        return out
    except urllib3.exceptions.HTTPError as e:
        logger.error("Error connecting to backend service: %s" % e, exc_info=e)
        flash(u'Error connecting to backend service.', 'danger')
        raise e
Пример #29
0
def flask_security_login2():
    u = row2dict(current_user)
    tk = current_user.get_auth_token()
    return jsonify({'user': u, 'token': tk})
Пример #30
0
def load_from_api(resource_name,
                  resource_id=None,
                  page=None,
                  return_everything=False,
                  fields=None,
                  params=None,
                  pagesize=None):
    """ Load data from the PMG API.

    :param str resource_name: resource to load (used as the start of the URL), or a full URL
    :param int resource_id: resource id (optional), appended to the resource name
    :param int page: page number to load (default is the first page)
    :param bool return_everything: fetch all pages? (default: False)
    :param list fields: list of field names to ask for (V2 only).
    :param dict params: additional query params
    :param int pagesize: items per page
    """
    params = {} if (params is None) else params
    # check for full URL?
    if resource_name.startswith('http'):
        resource_name = resource_name.split('/', 3)[3]

    v2 = resource_name.startswith('v2')
    if fields and not v2:
        raise ValueError("Fields parameter is only supported for API v2 urls.")

    query_str = resource_name
    if resource_id:
        query_str += "/" + str(resource_id)
    if not v2:
        query_str += '/'

    if page:
        params["page"] = str(page)
    if fields:
        params["fields"] = ','.join(fields)
    if pagesize:
        params["per_page"] = pagesize

    headers = {}
    # add auth header
    if current_user.is_authenticated():
        headers = {'Authentication-Token': current_user.get_auth_token()}

    try:
        response = http.request('GET',
                                API_URL + query_str,
                                headers=headers,
                                fields=params)

        if response.status == 404:
            abort(404)

        if response.status != 200 and response.status not in [401, 403]:
            try:
                msg = response_json(response).get('message')
            except Exception:
                msg = None

            raise ApiException(response.status, msg
                               or "An unspecified error has occurred.")

        out = response_json(response)
        if return_everything:
            next_response_json = out
            i = 0
            while next_response_json.get('next') and i < 1000:
                next_response = http.request('GET',
                                             next_response_json.get('next'),
                                             headers=headers)
                next_response_json = response_json(next_response)
                out['results'] += next_response_json['results']
                i += 1
            if out.get('next'):
                out.pop('next')

        return out
    except urllib3.exceptions.HTTPError as e:
        logger.error("Error connecting to backend service: %s" % e, exc_info=e)
        flash(u'Error connecting to backend service.', 'danger')
        raise e
Пример #31
0
def get_all_users():
    users = User.query.all()

    return response('User List', 'Full user list', 200,
                    users_schema.dump(users), current_user.get_auth_token())
Пример #32
0
def token():
    token = current_user.get_auth_token()
    return render_template('security/show_token.html', token=token)
Пример #33
0
def login_info():
    if current_user.is_authenticated:
        return json.dumps({"auth_token": current_user.get_auth_token()})
    else:
        app.logger.debug('Unsuccessful login attempt')
        return {"status": "Could Not Log In."}
Пример #34
0
def get_token():
    return jsonify(current_user.get_auth_token())
Пример #35
0
def auth_token():
    return current_user.get_auth_token()