Exemplo n.º 1
0
 def decorated_function(*args, **kwargs):
     remote_address = request.environ["REMOTE_ADDR"]
     client_address = request.environ.get("HTTP_X_FORWARDED_FOR",
                                          remote_address)
     rest_request = request.path.startswith("/rest/")
     endpoint = "/".join(request.path.split("/")[:2 + rest_request])
     request_property = f"{request.method.lower()}_requests"
     endpoint_rbac = vs.rbac[request_property].get(endpoint)
     if not current_user.is_authenticated:
         login_user(db.get_user("admin"))
     username = getattr(current_user, "name", "Unknown")
     if not endpoint_rbac:
         status_code = 404
     else:
         try:
             result = function(*args, **kwargs)
             status_code = 200
         except (db.rbac_error, Forbidden):
             status_code = 403
         except NotFound:
             status_code = 404
         except Exception:
             status_code, traceback = 500, format_exc()
     log = (f"USER: {username} ({client_address}) - "
            f"{request.method} {request.path} ({status_code})")
     if status_code == 500:
         log += f"\n{traceback}"
     env.log(Server.status_log_level[status_code],
             log,
             change_log=False)
     if status_code == 200:
         return result
     elif endpoint == "/login" or request.method == "GET" and not rest_request:
         if (not current_user.is_authenticated and not rest_request
                 and endpoint != "/login"):
             url = url_for("blueprint.route",
                           page="login",
                           next_url=request.url)
             return redirect(login_url(url))
         next_url = request.args.get("next_url")
         login_link = login_url(
             url_for("blueprint.route", page="login",
                     next_url=next_url))
         return (
             render_template("error.html",
                             error=status_code,
                             login_url=login_link),
             status_code,
         )
     else:
         error_message = Server.status_error_message[status_code]
         alert = f"Error {status_code} - {error_message}"
         return jsonify({"alert": alert}), status_code
Exemplo n.º 2
0
    def test_login_url_generation(self):
        PROTECTED = 'http://localhost/protected'

        self.assertEqual('/login?n=%2Fprotected',
                         login_url('/login', PROTECTED, 'n'))

        self.assertEqual('/login?next=%2Fprotected',
                         login_url('/login', PROTECTED))

        expected = 'https://auth.localhost/login' + \
                   '?next=http%3A%2F%2Flocalhost%2Fprotected'
        self.assertEqual(expected,
                         login_url('https://auth.localhost/login', PROTECTED))

        self.assertEqual('/login?affil=cgnu&next=%2Fprotected',
                         login_url('/login?affil=cgnu', PROTECTED))
Exemplo n.º 3
0
def pga_unauthorised():

    lm = current_app.login_manager
    login_message = None

    if lm.login_message:
        if lm.localize_callback is not None:
            login_message = lm.localize_callback(lm.login_message)
        else:
            login_message = lm.login_message

    if not lm.login_view or request.is_xhr:
        # Only 401 is not enough to distinguish pgAdmin login is required.
        # There are other cases when we return 401. For eg. wrong password
        # supplied while connecting to server.
        # So send additional 'info' message.
        return make_json_response(
            status=401,
            success=0,
            errormsg=login_message,
            info='PGADMIN_LOGIN_REQUIRED'
        )

    if login_message:
        flash(login_message, category=lm.login_message_category)

    return redirect(login_url(lm.login_view, request.url))
Exemplo n.º 4
0
def pga_unauthorised():

    lm = current_app.login_manager
    login_message = None

    if lm.login_message:
        if lm.localize_callback is not None:
            login_message = lm.localize_callback(lm.login_message)
        else:
            login_message = lm.login_message

    if not lm.login_view or request.is_xhr:
        # Only 401 is not enough to distinguish pgAdmin login is required.
        # There are other cases when we return 401. For eg. wrong password
        # supplied while connecting to server.
        # So send additional 'info' message.
        return make_json_response(status=401,
                                  success=0,
                                  errormsg=login_message,
                                  info='PGADMIN_LOGIN_REQUIRED')

    if login_message:
        flash(login_message, category=lm.login_message_category)

    return redirect(login_url(lm.login_view, request.url))
Exemplo n.º 5
0
    def test_login_url_generation(self):
        PROTECTED = 'http://localhost/protected'

        self.assertEqual('/login?n=%2Fprotected', login_url('/login',
                                                            PROTECTED, 'n'))

        self.assertEqual('/login?next=%2Fprotected', login_url('/login',
                                                               PROTECTED))

        expected = 'https://auth.localhost/login' + \
                   '?next=http%3A%2F%2Flocalhost%2Fprotected'
        self.assertEqual(expected,
                         login_url('https://auth.localhost/login', PROTECTED))

        self.assertEqual('/login?affil=cgnu&next=%2Fprotected',
                         login_url('/login?affil=cgnu', PROTECTED))
Exemplo n.º 6
0
def unauthorize_loader():
    '''callback method required by unautorized_handler of login_manager
       this method is executed, if authentication is failed or never login
        @return: redirect login page
    '''
    print('unauth')
    return redirect(login_url('login', request.url))
Exemplo n.º 7
0
    def unauthorized_callback():
        if request.method == 'GET':
            response = redirect(login_url('accounts.login',
                                           request.url))
            return response

        return redirect(url_for('accounts.login'))
 def decorated_function(request_id, *args, **kwargs):
     if not current_user.is_authenticated or current_user.is_anonymous:
         return redirect(
             login_url(login_manager.login_view, next_url=request.url))
     return f(request_id) if is_allowed(
         user=current_user,
         request_id=request_id,
         permission=permission) else abort(403)
Exemplo n.º 9
0
    def test_login_url_generation_with_view(self):
        app = Flask(__name__)
        login_manager = LoginManager()
        login_manager.init_app(app)

        @app.route('/login')
        def login():
            return ''

        with app.test_request_context():
            self.assertEqual('/login?next=%2Fprotected',
                             login_url('login', '/protected'))
Exemplo n.º 10
0
    def test_login_url_generation_with_view(self):
        app = Flask(__name__)
        login_manager = LoginManager()
        login_manager.init_app(app)

        @app.route('/login')
        def login():
            return ''

        with app.test_request_context():
            self.assertEqual('/login?next=%2Fprotected',
                             login_url('login', '/protected'))
Exemplo n.º 11
0
  def unauthorized():
    """Called when the user tries to access an endpoint guarded with
       login_required but they are not authorized.

       Endpoints like /dashboard, /program/1, etc. redirect the user to the
       /login page.

       Endpoints like /api /query, /import, etc. resolve with 401 UNAUTHORIZED
       and a simple json error object.
    """
    if (re.match(r'^(\/api|\/query|\/search)', request.path) or
       request.headers.get('X-Requested-By') == 'GGRC'):
      return json.dumps({'error': 'unauthorized'}), 401
    return redirect(login_url('/login', request.url))
Exemplo n.º 12
0
  def unauthorized():
    """Called when the user tries to access an endpoint guarded with
       login_required but they are not authorized.

       Endpoints like /dashboard, /program/1, etc. redirect the user to the
       /login page.

       Endpoints like /api /query, /import, etc. resolve with 401 UNAUTHORIZED
       and a simple json error object.
    """
    if (re.match(r'^(\/api|\/query|\/search)', request.path) or
       request.headers.get('X-Requested-By') == 'gGRC'):
      return json.dumps({'error': 'unauthorized'}), 401
    return redirect(login_url('/login', request.url))
Exemplo n.º 13
0
    def post(self):
        """ API interface for user registration """

        if not current_user.is_authenticated:
            return auth_ns.abort(401, _('Invalid user'))

        # load submitted data
        name = auth_ns.payload['name'] if 'name' in auth_ns.payload else ''
        email = auth_ns.payload['email'] if 'email' in auth_ns.payload else ''
        password = auth_ns.payload[
            'password'] if 'password' in auth_ns.payload else ''

        # mimic the SignupForm
        form = SignupForm(
            data={
                'name': name,
                'email': email,
                'password': password,
                'password2': password,
            })
        form.skip_csrf_validation()

        status_code = 200
        msg = ''

        # input data validation
        if form.validate_on_submit():
            usvc = UserService()
            user, token, error = usvc.register_user(name, email, password)
            if user and token:
                # triger activation email
                confirm_url = login_url(login_view=url_for(all_urls['login'],
                                                           _external=True),
                                        next_url=url_for(
                                            all_urls['confirm_email'],
                                            token=token.token))
                html = render_template('activate.html',
                                       confirm_url=confirm_url)
                subject = _('Please confirm your email')
                send_email(current_app, user.email, subject, html)

                return normal_response()
            else:
                status_code = 401
                msg = error or _('Unknown error in user registration')
        else:
            status_code = 401
            msg = form.extract_errors() or _('Invalid username or password')
        return auth_ns.abort(status_code, msg or _('Unknown error'))
Exemplo n.º 14
0
def signup():
    # Bypass Login screen if user is logged in
    if current_user.is_authenticated:
        return redirect(url_for(all_urls['home']))

    form = SignupForm()
    if request.method == 'POST' and form.validate_on_submit():
        name = request.form.get('name', None)
        email = request.form.get('email', None)
        password = request.form.get('password', None)
        password2 = request.form.get('password2', None)

        if password and password2 and password == password2:
            usvc = UserService()
            user, token, error = usvc.register_user(name, email, password)
            if user and token:
                # triger activation email
                confirm_url = login_url(
                    login_view=url_for(
                        all_urls['login'],
                        _external=True
                    ),
                    next_url=url_for(
                        all_urls['confirm_email'],
                        token=token.token
                    ))
                html = render_template(
                    'activate.html', confirm_url=confirm_url
                )
                subject = _('Please confirm your email')
                send_email(current_app, user.email, subject, html)

                flash(
                    _('Activation email has been sent to your email box. Please confirm your email first.'),
                    'info'
                )
                return redirect(request.args.get('next') or url_for(all_urls['login']))
            else:
                flash(error or _('Unknown error in user registration'), 'error')
        else:
            flash(_('Both passwords must be the same.'), 'error')
    return render_template(
        'signup.html',
        title=_('Sign Up'),
        form=form,
        url_login=url_for(all_urls['login']),
        url_signup=url_for(all_urls['signup'])
    )
Exemplo n.º 15
0
 def unauthorized():
     if not login_manager.login_view:
         abort(401)
     return redirect(login_url(login_manager.login_view, request.url))
 def decorated_function(request_id, *args, **kwargs):
     if not current_user.is_authenticated or current_user.is_anonymous:
         return redirect(login_url(login_manager.login_view,
                                   next_url=request.url))
     return f(request_id) if is_allowed(user=current_user, request_id=request_id,
                                        permission=permission) else abort(403)
Exemplo n.º 17
0
 def test_login_url_no_next_url(self):
     self.assertEqual(login_url('/foo'), '/foo')
Exemplo n.º 18
0
def get_response_content(response_id):
    """
    Currently only supports File Responses.

    Request Parameters:
    - token: (optional) ephemeral access token

    :return: response file contents or
             redirect to login if user not authenticated and no token provided or
             400 error if response/file not found
    """
    response_ = Responses.query.filter_by(id=response_id, deleted=False).one()

    if response_ is not None and response_.type == FILE:
        upload_path = os.path.join(
            current_app.config["UPLOAD_DIRECTORY"],
            response_.request_id
        )
        filepath_parts = (
            upload_path,
            response_.name
        )
        filepath = os.path.join(*filepath_parts)
        serving_path = os.path.join(
            current_app.config['UPLOAD_SERVING_DIRECTORY'],
            response_.request_id,
            response_.name
        )
        token = flask_request.args.get('token')
        if fu.exists(filepath):
            if response_.is_public:
                # then we just serve the file, anyone can view it
                @after_this_request
                def remove(resp):
                    os.remove(serving_path)
                    return resp

                return fu.send_file(*filepath_parts, as_attachment=True)
            else:
                # check presence of token in url
                if token is not None:
                    resptok = ResponseTokens.query.filter_by(
                        token=token, response_id=response_id).first()
                    if resptok is not None:
                        if response_.privacy != PRIVATE:
                            @after_this_request
                            def remove(resp):
                                os.remove(serving_path)
                                return resp

                            return fu.send_file(*filepath_parts, as_attachment=True)
                        else:
                            delete_object(resptok)

                # if token not included, nonexistent, or is expired, but user is logged in
                if current_user.is_authenticated:
                    # user is agency or is public and response is not private
                    if (((current_user.is_public and response_.privacy != PRIVATE)
                         or current_user.is_agency)
                            # user is associated with request
                            and UserRequests.query.filter_by(
                                request_id=response_.request_id,
                                user_guid=current_user.guid
                            ).first() is not None):
                        @after_this_request
                        def remove(resp):
                            os.remove(serving_path)
                            return resp

                        return fu.send_file(*filepath_parts, as_attachment=True)
                    # user does not have permission to view file
                    return abort(403)
                else:
                    # redirect to login
                    return redirect(login_url(
                        login_manager.login_view,
                        next_url=url_for('request.view', request_id=response_.request_id)
                    ))
    return abort(404)  # file does not exist
Exemplo n.º 19
0
def unauthorized():
    if request.method == 'GET':
        flash('Please log in to access this page', 'error')
        return redirect(login_url(url_for('login')))
Exemplo n.º 20
0
    def unauthorized():
        flash('Please log in to access this page.', 'error')

        return redirect(login_url('login', request.url))
Exemplo n.º 21
0
__author__ = 'mikec'

import uuid
from flask import Flask

app = Flask(__name__)
app.secret_key=uuid.uuid4().hex
app.secret_key='sdfsdgfsdgdfgfhggdfghdfgdfgdfg' # dev only - using a constant secret key allows session logins to remain logged in between server restarts

import flask_wtf
flask_wtf.CsrfProtect(app)

# Init flask-login:
from flask_login import LoginManager,login_url
login_manager = LoginManager()
login_manager.login_view=login_url('/login')
login_manager.init_app(app)

import os.path
app.config.from_pyfile( os.path.expanduser('~/.issues.cfg') )


upload_folder=os.path.abspath(os.path.join(os.path.dirname(__file__),'../uploads'))
print upload_folder

app.config['UPLOAD_FOLDER']=upload_folder
from flask_mail import Mail
mail=Mail(app)

import issues.auth
import issues.index
Exemplo n.º 22
0
def unauthorized_callback():
    if request.method == "GET":
        response = redirect(login_url("accounts.login", request.url))
        return response

    return redirect(url_for("accounts.login"))
Exemplo n.º 23
0
def unauthorized():
    if request.method == 'GET':
        return redirect(login_url('/login', request.url))
    else:
        return dict(error=True, message="Please Log In For Access"), 403
Exemplo n.º 24
0
def not_authorized(e):
    """send the user to the login screen when they try to access a locked page"""
    flash("Confirm Your Identity to Proceed")
    return redirect(login_url("/login", next_url=url_for(request.endpoint)))
Exemplo n.º 25
0
def get_response_content(response_id):
    """
    Currently only supports File Responses.

    Request Parameters:
    - token: (optional) ephemeral access token

    :return: response file contents or
             redirect to login if user not authenticated and no token provided or
             400 error if response/file not found
    """
    response_ = Responses.query.filter_by(id=response_id, deleted=False).one()

    if response_ is not None and response_.type == FILE:
        upload_path = os.path.join(
            current_app.config["UPLOAD_DIRECTORY"],
            response_.request_id
        )
        filepath_parts = (
            upload_path,
            response_.name
        )
        filepath = os.path.join(*filepath_parts)
        serving_path = os.path.join(
            current_app.config['UPLOAD_SERVING_DIRECTORY'],
            response_.request_id,
            response_.name
        )
        token = flask_request.args.get('token')
        if fu.exists(filepath):
            if response_.is_public:
                # then we just serve the file, anyone can view it
                @after_this_request
                def remove(resp):
                    os.remove(serving_path)
                    return resp

                return fu.send_file(*filepath_parts, as_attachment=True)
            else:
                # check presence of token in url
                if token is not None:
                    resptok = ResponseTokens.query.filter_by(
                        token=token, response_id=response_id).first()
                    if resptok is not None:
                        if response_.privacy != PRIVATE:
                            @after_this_request
                            def remove(resp):
                                os.remove(serving_path)
                                return resp

                            return fu.send_file(*filepath_parts, as_attachment=True)
                        else:
                            delete_object(resptok)

                # if token not included, nonexistent, or is expired, but user is logged in
                if current_user.is_authenticated:
                    # user is agency or is public and response is not private
                    if (((current_user.is_public and response_.privacy != PRIVATE)
                         or current_user.is_agency)
                            # user is associated with request
                            and UserRequests.query.filter_by(
                                request_id=response_.request_id,
                                user_guid=current_user.guid
                            ).first() is not None):
                        @after_this_request
                        def remove(resp):
                            os.remove(serving_path)
                            return resp

                        return fu.send_file(*filepath_parts, as_attachment=True)
                    # user does not have permission to view file
                    return abort(403)
                else:
                    # redirect to login
                    return redirect(login_url(
                        login_manager.login_view,
                        next_url=url_for('request.view', request_id=response_.request_id)
                    ))
    return abort(404)  # file does not exist
Exemplo n.º 26
0
    def unauthorized():
        flash('Please log in to access this page.', 'error')

        return redirect(login_url('login', request.url))
Exemplo n.º 27
0
def unauthorized():
    if request.method == 'GET':
        return redirect(login_url('auth.login', request.url))
    else:
        return dict(error=True, message="Please log in for access."), 403
Exemplo n.º 28
0
def unauthorized():
    if request.method == 'GET':
        flash('Please log in to access this page')
        return redirect(login_url('auth.login', request.url))
    else:
        return dict(error=True, message="Please log in for access."), 403
Exemplo n.º 29
0
def unauthorized():
    return redirect(login_url('login', request.url))
Exemplo n.º 30
0
 def _handle_view(self, *args, **kwargs):  # noqa
     """Admin views requires login"""
     if current_app.config.get('ADMIN_REQUIRES_LOGIN') is True:
         if not current_user.is_authenticated:
             return redirect(login_url('quokka.login', next_url="/admin"))
Exemplo n.º 31
0
 def test_login_url_no_next_url(self):
     self.assertEqual(login_url('/foo'), '/foo')
Exemplo n.º 32
0
def unauthorized_callback():
    return redirect(login_url("login", request.url))