def app_spotify_login(flask_app): spotify_blueprint = make_spotify_blueprint( os.getenv("SPOTIPY_CLIENT_ID"), os.getenv("SPOTIPY_CLIENT_SECRET"), 'user-library-read playlist-modify-private playlist-read-private ' 'user-modify-playback-state user-read-playback-state', os.getenv("SPOTIPY_REDIRECT_URI")) flask_app.register_blueprint(spotify_blueprint, url_prefix='/login')
def test_load_from_config(): app = Flask(__name__) app.secret_key = "anything" app.config["SPOTIFY_OAUTH_CLIENT_ID"] = "foo" app.config["SPOTIFY_OAUTH_CLIENT_SECRET"] = "bar" spotify_bp = make_spotify_blueprint(redirect_to="index") app.register_blueprint(spotify_bp) resp = app.test_client().get("/spotify") url = resp.headers["Location"] client_id = URLObject(url).query.dict.get("client_id") assert client_id == "foo"
def test_context_local(): responses.add(responses.GET, "https://google.com") # set up two apps with two different set of auth tokens app1 = Flask(__name__) spotify_bp1 = make_spotify_blueprint( "foo1", "bar1", redirect_to="url1", backend=MemoryBackend({"access_token": "app1"}), ) app1.register_blueprint(spotify_bp1) app2 = Flask(__name__) spotify_bp2 = make_spotify_blueprint( "foo2", "bar2", redirect_to="url2", backend=MemoryBackend({"access_token": "app2"}), ) app2.register_blueprint(spotify_bp2) # outside of a request context, referencing functions on the `spotify` object # will raise an exception with pytest.raises(RuntimeError): spotify.get("https://google.com") # inside of a request context, `spotify` should be a proxy to the correct # blueprint session with app1.test_request_context("/"): app1.preprocess_request() spotify.get("https://google.com") request = responses.calls[0].request assert request.headers["Authorization"] == "Bearer app1" with app2.test_request_context("/"): app2.preprocess_request() spotify.get("https://google.com") request = responses.calls[1].request assert request.headers["Authorization"] == "Bearer app2"
def test_blueprint_factory(): spotify_bp = make_spotify_blueprint( client_id="foo", client_secret="bar", scope="user-read-private", redirect_to="index", ) assert isinstance(spotify_bp, OAuth2ConsumerBlueprint) assert spotify_bp.session.scope == "user-read-private" assert spotify_bp.session.base_url == "https://api.spotify.com" assert spotify_bp.session.client_id == "foo" assert spotify_bp.client_secret == "bar" assert spotify_bp.authorization_url == "https://accounts.spotify.com/authorize" assert spotify_bp.token_url == "https://accounts.spotify.com/api/token"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') # conn = psycopg2.connect(os.environ.get('DATABASE_URL'), sslmode='require') sqldb.init_app(app) login_manager = LoginManager(app) dbInterface = Database(current_user) migrate = Migrate(app, sqldb, render_as_batch=True) manager = Manager(app) manager.add_command('db', MigrateCommand) scope = "user-read-recently-played" blueprint = make_spotify_blueprint( client_id=os.environ.get('SPOTIPY_CLIENT_ID'), client_secret=os.environ.get('SPOTIPY_CLIENT_SECRET'), scope=["user-read-recently-played", "user-read-email", "user-top-read"], redirect_url="/discover", storage=SQLAlchemyStorage(OAuth, sqldb.session, user=current_user, user_required=False)) app.register_blueprint(blueprint=blueprint, url_prefix='/log_in') SEASONS = { 1: 'Winter', 2: 'Winter', 3: 'Spring', 4: 'Spring', 5: 'Spring', 6: 'Summer', 7: 'Summer', 8: 'Summer',
import os from dotenv import load_dotenv from flask import Flask from flask_dance.contrib.spotify import make_spotify_blueprint from . import alembic, db, jwt_manager from .utils.spotify import SPOTIFY_SCOPES from .views.auth import auth_api from .views.testing import testing_api app = Flask(__name__) load_dotenv() app.config.from_object( f"spotifyfavouritesmanager.config.{os.environ.get('FLASK_CONFIG','DEVELOPMENT')}" ) db.init_app(app) alembic.init_app(app) jwt_manager.init_app(app) app.register_blueprint(auth_api) app.register_blueprint(testing_api) spotify_blueprint = make_spotify_blueprint( client_id=app.config["SPOTIFY_CLIENT_ID"], client_secret=app.config["SPOTIFY_CLIENT_SECRET"], scope=" ".join(SPOTIFY_SCOPES), ) app.register_blueprint(spotify_blueprint, prefix="/oauth")
from flask import ( Blueprint, redirect, render_template, session, url_for, ) import flask_dance.consumer from flask_dance.contrib.spotify import make_spotify_blueprint, spotify spotify_bp = make_spotify_blueprint(scope="user-top-read") @flask_dance.consumer.oauth_authorized.connect_via(spotify_bp) def spotify_logged_in(blueprint, token): session.clear() profile = spotify.get("v1/me").json() session["user_id"] = profile["id"] app = Blueprint("auth", __name__, url_prefix="/") @app.route("/") def index(): if spotify.authorized: return render_template("authorized.html") else: return render_template("unauthorized.html")
CONFIG_FILE = 'auth.yaml' with open(CONFIG_FILE, 'r') as config_file: config = yaml.load(config_file, Loader=yaml.FullLoader) secret_key = config['session']['secret_key'] client_id = config['spotify']['client_id'] client_secret = config['spotify']['client_secret'] scope = 'user-library-read,playlist-modify-private,user-top-read,playlist-read-private,playlist-read-collaborative' os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1' app = flask.Flask(__name__) app.config['PROPAGATE_EXCEPTIONS'] = False app.secret_key = secret_key blueprint = make_spotify_blueprint(client_id=client_id, client_secret=client_secret, scope=scope) app.register_blueprint(blueprint, url_prefix='/login') # app.config.from_object(__name__) CORS(app, supports_credentials=True) def get_playlist_id(playlist_input: str) -> str: # Spotipy already supports different ID types if len(playlist_input) == 22: return playlist_input if not playlist_input.startswith('http'): playlist_id = playlist_input.split(':')[2] return playlist_id else:
def _make_app(*args, **kwargs): app = Flask(__name__) app.secret_key = "whatever" blueprint = make_spotify_blueprint(*args, **kwargs) app.register_blueprint(blueprint) return app
app.config['KBL_FOLDER'] = KBL_FOLDER # Logging config handler = logging.handlers.RotatingFileHandler( 'log/app.log', maxBytes=104857600, backupCount=20 ) logging_format = logging.Formatter( '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s' ) handler.setFormatter(logging_format) app.logger.addHandler(handler) # OAuth blueprint spotify_blueprint = make_spotify_blueprint( client_id=SPOTIFY_APP_ID, client_secret=SPOTIFY_APP_SECRET, scope='user-read-email playlist-read-private', ) kkbox_blueprint = make_kkbox_blueprint( client_id=KKBOX_APP_ID, client_secret=KKBOX_APP_SECRET, authorization_url_params={'grant_type': 'client_credentials'}, ) app.register_blueprint(spotify_blueprint, url_prefix="/login") app.register_blueprint(kkbox_blueprint, url_prefix="/login") # Utility function def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1] == 'kbl'
from flask import Flask, render_template, request, redirect, url_for from flask_dance.contrib.spotify import make_spotify_blueprint, spotify from flask_bootstrap import Bootstrap import requests, json, urllib.parse app = Flask(__name__) app.secret_key = 'development' Bootstrap(app) blueprint = make_spotify_blueprint( client_id='613f80f4035d442ea0b02a78556d7dfa', client_secret='e28971afbee14756871d5eb08c5e5a6c', scope='playlist-modify-public streaming user-library-read', ) app.register_blueprint(blueprint, url_prefix='/login') @app.route('/') def index(): if not spotify.authorized: return redirect(url_for('spotify.login')) search_string = urllib.parse.quote('The Birthday Party') resp = spotify.get(f'v1/search?q={search_string}&type=artist') return render_template('home.html', data=resp.json())
from flask import Flask, render_template, request, redirect, url_for from flask_dance.contrib.spotify import make_spotify_blueprint, spotify from flask_bootstrap import Bootstrap import requests, json, urllib.parse blueprint = make_spotify_blueprint( client_id='6bcc1e7cb9da4fe09feb3375b227c9fb', client_secret='2fbb802629a6472e8701f73999b491f3', scope='playlist-modify-public streaming user-library-read', ) app = Flask(__name__) app.secret_key = 'development' Bootstrap(app) # authentication keys in authenticate.py in same dir # (not in github repo) # go to: https://developer.spotify.com/dashboard/applications #blueprint = make_spotify_blueprint( # client_id='..client key..', # client_secret='..client secret..', # scope='playlist-modify-public streaming user-library-read', #) app.register_blueprint(blueprint, url_prefix='/login') @app.route('/') def index(): if not spotify.authorized: return redirect(url_for('spotify.login'))
from flask import Flask, render_template, request, redirect, url_for from flask_dance.contrib.spotify import make_spotify_blueprint, spotify from flask_bootstrap import Bootstrap import requests, json, urllib.parse import spotipy as sp import requests, json from pprint import pprint #import smiledetector as sd blueprint = make_spotify_blueprint( client_id='16c88d48f61648acb6f1b11b28c1141b', client_secret='26b4701201704cf99ebe5f39184f14d4', scope='playlist-modify-public streaming user-library-read', ) app = Flask(__name__) app.secret_key = 'development' Bootstrap(app) app.register_blueprint(blueprint, url_prefix='/login') @app.route('/') def homepage(): if not spotify.authorized: return redirect(url_for('spotify.login')) html = render_template('home.html') return html def index():
#CST 205 Project #run with this export OAUTHLIB_INSECURE_TRANSPORT=1 from flask import Flask, render_template, request, redirect, url_for from flask_dance.contrib.spotify import make_spotify_blueprint, spotify from oauthlib.oauth2.rfc6749.errors import InvalidGrantError, TokenExpiredError, OAuth2Error import requests, json, urllib.parse #Initializes the flask app, sets the static folder in order to use our styles and adds the secret key to be used with spotify. app = Flask(__name__, static_folder="static") app.secret_key = 'development' #Creates the spotify blueprint in order to give the API our developer account credentials. blueprint = make_spotify_blueprint( client_id='9d09c92238a545bcb83abf4b3427c7d5', client_secret='889faecbb3ee4e1196a76e5e617e802c', scope='playlist-modify-public streaming user-library-read', ) #Sets the questions that will be included in the survey. questions = [ "I am a very sociable person.", "I like to party.", "I am energetic.", "I enjoy dancing.", "I enjoy happy songs.", "I enjoy instrumental songs." ] #Registers the bluepring in order to connect to the Spotify API app.register_blueprint(blueprint, url_prefix='/login') #The landing page in which the user takes the survey. In the render_template function the questions are also passed. @app.route('/')
from flask import flash from flask_login import current_user, login_user from flask_dance.contrib.spotify import make_spotify_blueprint from flask_dance.consumer import oauth_authorized, oauth_error from flask_dance.consumer.storage.sqla import SQLAlchemyStorage from sqlalchemy.orm.exc import NoResultFound from models import db, User, OAuth blueprint = make_spotify_blueprint( scope= "user-read-email user-read-private user-read-playback-state user-read-currently-playing", storage=SQLAlchemyStorage(OAuth, db.session, user=current_user), ) @oauth_authorized.connect_via(blueprint) def spotify_logged_in(blueprint, token): if not token: msg = "Failed to log in." flash(msg, category="error") return False resp = blueprint.session.get("/v1/me") if not resp.ok: msg = "Failed to fetch user info." flash(msg, category="error") return False info = resp.json() user_id = info["id"]
from flask import jsonify from app import app from models import User from authorization import login_required # from flask_oauth import OAuth from flask import session from flask import redirect, url_for from flask_dance.contrib.spotify import make_spotify_blueprint, spotify blueprint = make_spotify_blueprint( client_id="24ccca945de24c6585489665bfa7521b", client_secret="ce62b08bb5e44ecc9856a4f6a01696f5", scope=[ 'user-read-recently-played', 'user-read-email', 'user-read-private' ], redirect_url='http://*****:*****@app.route("/api/auth-login") def index(): if not spotify.authorized: return redirect(url_for("spotify.login")) resp = spotify.get("/user") assert resp.ok return "You are @{login} on Spotify".format(login=resp.json()["login"]) @app.route("/api/callback") def authed_handler(): return "Authorized successfully!"