コード例 #1
0
def post_account_login():
    """
        First we need to verify the request contains a username and a password
        if not, then we must display an error.
        :return:
    """
    app.logger.info('Reading credentials from request...')
    username = request.form['username']
    password = request.form['password']

    if username is None:
        return render_template("authentication/login.html",
                               error="Debe proporcionar un usuario")
    if password is None:
        return render_template("authentication/login.html",
                               error="Debe proporcionar una contrasena")

    app.logger.info('Credentials OK, now authenticating...')

    user = get_user_by_username(username)
    if user is None:
        return render_template(
            "authentication/login.html",
            error="No se ha encontrado el usuario proporcionado")

    if user.authenticate(password):
        app.logger.info('Credentials are correct...')
        session['logged_in'] = True
        login_user(user)
        return redirect(url_for('get_dashboard_root'))
    else:
        app.logger.info('Credentials are not correct...')
        error = "Su contraseña no es correcta"
        return render_template("authentication/login.html", error=error)
コード例 #2
0
def post_add_band():
    
    try:

        band = Band(
            band_id = uuid.uuid4(),
            name = request.form['name'],
            description = request.form['description'],
            genres = request.form['genres'],
            logo_url = request.form['logo']
            
        )
        
        band.set_founded(
            day = request.form['day'],
            month = request.form['month'],
            year = request.form['year']
        )
        band.save()
        user = get_user_by_username(current_user.username)
        user.bands.connect(band)
        user.save()
        band.members.connect(user)
        band.save()
        return redirect(url_for('get_dashboard_root'))
    except Exception as e:
        print(e)
        return render_template(
            "band/add.html", 
            error= "Error processing request"
        )
コード例 #3
0
def post_account():

    # First we verify the request is an actual json request. If not, then we
    # responded with a HTTP 400 Bad Request result code.
    if not request.is_json:
        app.logger.warning(
            'Request without JSON payload received on token endpoint')
        return jsonify({"msg": "Only JSON request is supported"}), 400

    # If we get here, is because the request contains valid json so we can
    # parse the parameters
    account_data = request.get_json()

    if 'username' in account_data and get_user_by_username(
            user_name=account_data['username']) is not None:
        return jsonify({"msg": "The provided username is not valid"}), 400

    user = create_user(account_data=account_data)

    # Now we verify that all required values are present and build a new instance
    # of user. If the instance is None, then one of the validations failed so
    # an HTTP BAD REQUEST status code should be returned
    if user is not None:
        # We try to create an instance
        try:
            # We try to persist the user account in Mongo Database
            user.save()

            return jsonify({
                'user_id': user.user_id,
                'username': user.username
            }), 201
        except NotUniqueError as nue:
            app.logger.error(
                "A request tried to use an already existing username.")
            return jsonify({"msg": "Username or email are not available"}), 400
        except ValidationError as ve:
            app.logger.error(
                "An error occurred while trying to create a user account. Error: "
                + ve.message)
            return jsonify({"msg": "The request failed to validate"}), 400
        except:
            app.logger.error(
                "An error occurred while trying to create a user account. Error: "
                + str(sys.exc_info()[0]))
            return jsonify({
                "msg":
                "The server cannot complete the account creation process"
            }), 500
    else:
        return jsonify({
            "msg":
            "One or more of the required values is not present in the request"
        }), 400
コード例 #4
0
def get_dashboard_root():
    """
        Gets the main application dashboard view if the user is already 
        authenticated.
        :return: Status response json
    """

    user = get_user_by_username(current_user.username)
    bands = user.bands.all()

    return render_template("dashboard/index.html", bands=bands)
コード例 #5
0
def post_token():
    """
        Receives authentication credentials in order to generate an access
        token to be used to access protected models. Tokens generated
        by this endpoint are JWT Tokens.
    """

    # First we verify the request is an actual json request. If not, then we
    # responded with a HTTP 400 Bad Request result code.
    if not request.is_json:
        app.logger.warning(
            'Request without JSON payload received on token endpoint')
        return jsonify({"msg": "Only JSON request is supported"}), 400

    # Read credentials from json request
    params = request.get_json()

    # Try to ready username and password properties. If one of them is not found,
    # then we generate an error and stop execution.

    username = params.get('username', None)
    password = params.get('password', None)

    if not username:
        app.logger.warning(
            'Request without username parameter received on token endpoint')
        return jsonify({"msg": "A username parameter must be provided"}), 400
    if not password:
        app.logger.warning(
            'Request without password parameter received on token endpoint')
        return jsonify({"msg": "A password parameter must be provided"}), 400

    # If we get here, is because a username and password credentials were
    # provided, so now we must verify them.

    user = get_user_by_username(username)

    if user is not None:
        if user.authenticate(password):

            # ACCESS TOKEN
            access_token_expires = app.config[
                'JWT_ACCESS_TOKEN_VALIDITY_HOURS']
            access_token = create_access_token(
                identity=user.user_id, expires_delta=access_token_expires)

            # REFRESH TOKEN
            refresh_token_expires = app.config[
                'JWT_REFRESH_TOKEN_VALIDITY_DAYS']
            refresh_token = create_refresh_token(
                identity=user.user_id, expires_delta=refresh_token_expires)

            app.logger.info('A new token has been generated for user [' +
                            user.user_id + "]")

            return jsonify({
                'access_token': access_token,
                'expiration': access_token_expires.total_seconds(),
                'refresh_token': refresh_token
            }), 200
    else:
        app.logger.warning('Request with invalid username was received')
        return jsonify(
            {"msg":
             "Unable to find user with [" + username + "] username"}), 404