Exemple #1
0
    def post(self):
        form = LoginForm()
        if form.validate_on_submit():
            login_user(form.user, remember=False)
            after_this_request(_commit)

        return _make_response(form, include_auth_token=True)
Exemple #2
0
    def post(self):
        form = LoginForm()
        if form.validate_on_submit():
            login_user(form.user, remember=False)
            after_this_request(_commit)

        return _make_response(form, include_auth_token=True)
Exemple #3
0
def get_user(username, password, *args, **kwargs):
    # This is only necessary for the `password` grant type.
    form = LoginForm(MultiDict({
        'email': username,
        'password': password
    }),
                     csrf_enabled=False)
    if form.validate_on_submit():
        return User.query.filter_by(email=username).first()
    return None
Exemple #4
0
def index():
    form = LoginForm()
    if request.method == "POST":
        if form.validate_on_submit():
            login_user(form.user, remember=form.remember.data)
    print 'errors: {}'.format(form.errors)
    print 'email: {}'.format(form.email)
    print 'is_submitted: {}'.format(form.is_submitted)

    return render_template('index.html', login_user_form=form)
    def login_view(self):
        # handle user login
        form = LoginForm(request.form)
        if helpers.validate_form_on_submit(form):
            if form.validate():
                login_user(form.user)

        if current_user.is_authenticated():
            return redirect(url_for('.index'))
        return redirect(url_for_security('login', next=url_for('.index')))
def login():
    form = LoginForm()
    print request.args
    if form.validate_on_submit():
        # login and validate the user...
        login_user(form.user, remember=form.remember.data)
        flash("Bienvenido!")
        return redirect(form.next.data)
    next_s = request.args.get("next")
    if request.method == "POST":
        flash(u"Contraseña o Usuario incorrecto. Intente nuevamente.")
    return render_template("login.html", form=form, next=next_s)
Exemple #7
0
def login():
    if current_user.is_authenticated():
        return redirect(request.referrer or '/')
    
    form = LoginForm()

    if form.validate_on_submit():
        login_user(form.user, remember=form.remember.data)
        return redirect(get_post_login_redirect())

        

    return render_template('security/login.html', 
                                active_nav_band = "Login",
                                form=form)
Exemple #8
0
    def login():
        if current_user.is_authenticated():
            return redirect('/')

        return render_template('login.html',
                               content='Login Page',
                               form=LoginForm())
Exemple #9
0
def user_context_processor():
    if current_user.is_authenticated():
        user = current_user._get_current_object()
    else:
        user = None
    return {
        'user': user,
        'login_user_form': LoginForm(),
        'register_form': RegisterForm(),
    }
Exemple #10
0
def login():
    """For GET requests, display the login form. For POSTS, login the current user
    by processing the form."""
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.get(form.email.data)
        if user:
            if pwd_context.encrypt(form.password.data) == user.password:
                user.authenticated = True
                db.session.add(user)
                db.session.commit()
                login_user(user, remember=True)
                flash('Logged in successfully.')
                next_url = request.args.get('next')
                # next_is_valid should check if the user has valid
                # permission to access the `next` url
                if not is_safe_url(next):
                    return abort(400)
                return redirect(next_url or url_for('index'))
    return render_template("security/login_user.html", form=form)
Exemple #11
0
def login():
    # app.logger.debug("login view")
    if g.logged_in:
        app.logger.debug("(already) logged in.")
        return redirect(url_for('index'))

    form = LoginForm()
    if form.validate_on_submit():
        app.logger.debug("login form validated.")
        # User has supplied login stuff... correctly?
        session['remember_me'] = form.remember_me.data
        o = oid.try_login(form.openid.data, ask_for = ['nickname', 'email'])
        print >>stderr, "oid.try_login() returned", repr(o)
        return o

    else:
        # User hasn't logged in or has left something blank or incorrect.
        return render_template(
            'login.html',
            content='Login Page',
            form=form,
            providers = app.config['OPENID_PROVIDERS'],
            )
Exemple #12
0
def login():
    form = LoginForm()
    if request.method == "POST" and "username" in request.form:
        username = request.form["username"]
        password = request.form["password"]
        remember = request.form.get("remember", "no") == "yes"

        user = User.query.filter_by(username=username,
                                    password=password).first()
        # TODO Hash password for check
        if user:
            if login_user(user, remember=remember):
                flash("Logged in!")
                return redirect(request.args.get("next") or url_for("index"))
            else:
                flash("Sorry, but you could not log in.")
        else:
            flash("Invalid username.")
    return render_template("login.html", form=form)
Exemple #13
0
def inject_userForms():
    return dict(login_form=LoginForm(), register_user_form=RegisterForm(), \
        forgot_password_form=ForgotPasswordForm(), change_password_form=ChangePasswordForm())
Exemple #14
0
def login():
    if current_user.is_authenticated():
        return redirect(request.referrer or '/')

    return render_template('login.html', form=LoginForm())
Exemple #15
0
 def login():
     return render_template('login.html',
                            content='Login Page',
                            form=LoginForm())
Exemple #16
0
def login():
    return render_template('login.html', form=LoginForm())
Exemple #17
0
 def custom_login():
     return render_template('login.html',
                            content='Custom Login Page',
                            form=LoginForm())
Exemple #18
0
def authorize(*args, **kwargs):
    """
    Authorization endpoint for OAuth2.
    Successful interaction with this endpoint yields an access token
    for the requesting client.

    Please note that I am not very confident of this current approach's
    security; it involves a shaky workaround to implement the resource owner
    password credentials (ROPC) OAuth2 flow for the official mobile app.

    Mobile applications are considered "public" clients because their client
    credentials (client id and client secret) cannot reliably be kept secure,
    since if they are bundled with the application they are potentially accessible
    to anyone who has the app on their phone.

    But the ROPC flow works like this:

        * User opens the mobile app and is greated with a native login view.
        * User enters their credentials and hits "Login".
        * POST to `/oauth/authorize?client_id=<CLIENT_ID>&response_type=code&grant_type=resource_owner_credentials&scope=userinfo&redirect_uri=<your redirect uri>`, with data: `{"email": <user email>, "password": <user password>}`
        * Server finds client with the specified client id, checks that the client is allowed the ROPC grant type, and if so, authenticates the user with the provided credentials.
        * If successful, the server responds with the header `Location: <your redirect uri>/?code=<your authorization code>`
        * In the mobile app, you can extract the authorization code and exchange it for the access token by sending a GET request to `/oauth/token?code=<your authorization code>&grant_type=authorization_code&client_id=<your client_id>&redirect_uri=<your redirect uri>`
        * If successful, the server responds with something like: `{"refresh_token": "Z9QAolFevdLXjO7OR1ImJ1pkqc248j", "scope": "userinfo", "access_token": "wvjTny7CXEVEQSfyxC1MSP11NEPnlj", "token_type": "Bearer"}`

    Clearly this is not the ideal flow and not really according to OAuth2 specifications. Anyone can discover and use the client id to imitate the official client since there is no (and cannot be any) verification of client authenticity with a client secret. Unless the provider server is secured with SSL/HTTPS, passwords are sent out in the open. It is only a temporary solution.

    A potential long-term solution is to use OAuth2's "client credentials" flow and consider each *installation* of the mobile application as a *separate* client. Thus each installation has its own unique client id and client secret, relevant only for that particular user. This still may not be very good (haven't thought it all the way through).

    For some more info see:

        * https://stackoverflow.com/questions/14574846/client-authentication-on-public-client
        * https://stackoverflow.com/questions/6190381/how-to-keep-the-client-credentials-confidential-while-using-oauth2s-resource-o
    """

    # NB: request.values refers to values from both
    # the response body and the url parameters.
    client_id = request.values.get('client_id')
    client = Client.query.get(client_id)
    grant_type = request.values.get('grant_type')

    # Check to see if the requested scope(s) are permitted
    # for this client.
    # Since this is a workaround (see below), this looks a bit weird.
    # But if the expected kwargs isn't processed (flask_oauthlib only processes them
    # if it is a GET request), collect the scope information another way.
    #        GET                    POST
    scopes = kwargs.get('scopes') or request.values.get('scope').split()
    client.validate_scopes(scopes)

    # Check to see if the requested grant type is permitted
    # for this client.
    client.validate_grant_type(grant_type)

    if request.method == 'GET':
        kwargs['client'] = client
        if grant_type == 'authorization_code':
            # The user must authenticate herself,
            # if not already authenticated.
            if not current_user.is_authenticated():
                return redirect(url_for('security.login', next=url_for('authorize')))

            kwargs['user'] = current_user

            return render_template('authorize.html', **kwargs)

        response = jsonify({'message': 'Invalid grant type for this request. Perhaps you mean a grant_type of `authorization_code`?'})
        response.status_code = 400
        return response

    elif request.method == 'POST':

        # Authenticate on behalf of the user.
        # ONLY TRUSTED CLIENTS should be allowed this grant type.
        # i.e. only official clients, all others should be using
        # grant type of `authorization_code`.
        # This is enforced since clients are by default restrited to only
        # the `authorization_code` grant type, unless explicitly set otherwise.
        # Note: this is a workaround since flask_oauthlib does not support the "password"
        # grant type at the moment (which is equivalent to "resource_owner_credentials").
        if grant_type == 'resource_owner_credentials':
            form = LoginForm(request.form, csrf_enabled=False)
            if form.validate_on_submit():
                login_user(form.user)
                return True
            else:
                print(form.errors)
                return False

        # Otherwise, assume this request is coming from
        # the authorization_code's authorize form.
        else:
            confirm = request.form.get('confirm', 'no')
            return confirm == 'yes'
Exemple #19
0
def get_user(username, password, *args, **kwargs):
    # This is only necessary for the `password` grant type.
    form = LoginForm(MultiDict({'email': username, 'password': password}), csrf_enabled=False)
    if form.validate_on_submit():
        return User.query.filter_by(email=username).first()
    return None
Exemple #20
0
def authorize(*args, **kwargs):
    """
    Authorization endpoint for OAuth2.
    Successful interaction with this endpoint yields an access token
    for the requesting client.

    Please note that I am not very confident of this current approach's
    security; it involves a shaky workaround to implement the resource owner
    password credentials (ROPC) OAuth2 flow for the official mobile app.

    Mobile applications are considered "public" clients because their client
    credentials (client id and client secret) cannot reliably be kept secure,
    since if they are bundled with the application they are potentially accessible
    to anyone who has the app on their phone.

    But the ROPC flow works like this:

        * User opens the mobile app and is greated with a native login view.
        * User enters their credentials and hits "Login".
        * POST to `/oauth/authorize?client_id=<CLIENT_ID>&response_type=code&grant_type=resource_owner_credentials&scope=userinfo&redirect_uri=<your redirect uri>`, with data: `{"email": <user email>, "password": <user password>}`
        * Server finds client with the specified client id, checks that the client is allowed the ROPC grant type, and if so, authenticates the user with the provided credentials.
        * If successful, the server responds with the header `Location: <your redirect uri>/?code=<your authorization code>`
        * In the mobile app, you can extract the authorization code and exchange it for the access token by sending a GET request to `/oauth/token?code=<your authorization code>&grant_type=authorization_code&client_id=<your client_id>&redirect_uri=<your redirect uri>`
        * If successful, the server responds with something like: `{"refresh_token": "Z9QAolFevdLXjO7OR1ImJ1pkqc248j", "scope": "userinfo", "access_token": "wvjTny7CXEVEQSfyxC1MSP11NEPnlj", "token_type": "Bearer"}`

    Clearly this is not the ideal flow and not really according to OAuth2 specifications. Anyone can discover and use the client id to imitate the official client since there is no (and cannot be any) verification of client authenticity with a client secret. Unless the provider server is secured with SSL/HTTPS, passwords are sent out in the open. It is only a temporary solution.

    A potential long-term solution is to use OAuth2's "client credentials" flow and consider each *installation* of the mobile application as a *separate* client. Thus each installation has its own unique client id and client secret, relevant only for that particular user. This still may not be very good (haven't thought it all the way through).

    For some more info see:

        * https://stackoverflow.com/questions/14574846/client-authentication-on-public-client
        * https://stackoverflow.com/questions/6190381/how-to-keep-the-client-credentials-confidential-while-using-oauth2s-resource-o
    """

    # NB: request.values refers to values from both
    # the response body and the url parameters.
    client_id = request.values.get('client_id')
    client = Client.query.get(client_id)
    grant_type = request.values.get('grant_type')

    # Check to see if the requested scope(s) are permitted
    # for this client.
    # Since this is a workaround (see below), this looks a bit weird.
    # But if the expected kwargs isn't processed (flask_oauthlib only processes them
    # if it is a GET request), collect the scope information another way.
    #        GET                    POST
    scopes = kwargs.get('scopes') or request.values.get('scope').split()
    client.validate_scopes(scopes)

    # Check to see if the requested grant type is permitted
    # for this client.
    client.validate_grant_type(grant_type)

    if request.method == 'GET':
        kwargs['client'] = client
        if grant_type == 'authorization_code':
            # The user must authenticate herself,
            # if not already authenticated.
            if not current_user.is_authenticated():
                return redirect(
                    url_for('security.login', next=url_for('authorize')))

            kwargs['user'] = current_user

            return render_template('authorize.html', **kwargs)

        response = jsonify({
            'message':
            'Invalid grant type for this request. Perhaps you mean a grant_type of `authorization_code`?'
        })
        response.status_code = 400
        return response

    elif request.method == 'POST':

        # Authenticate on behalf of the user.
        # ONLY TRUSTED CLIENTS should be allowed this grant type.
        # i.e. only official clients, all others should be using
        # grant type of `authorization_code`.
        # This is enforced since clients are by default restrited to only
        # the `authorization_code` grant type, unless explicitly set otherwise.
        # Note: this is a workaround since flask_oauthlib does not support the "password"
        # grant type at the moment (which is equivalent to "resource_owner_credentials").
        if grant_type == 'resource_owner_credentials':
            form = LoginForm(request.form, csrf_enabled=False)
            if form.validate_on_submit():
                login_user(form.user)
                return True
            else:
                print(form.errors)
                return False

        # Otherwise, assume this request is coming from
        # the authorization_code's authorize form.
        else:
            confirm = request.form.get('confirm', 'no')
            return confirm == 'yes'