def loginWithSpotify(): from index import db, user access_token_spotify = request.json["access_token_spotify"] access_token = request.json["access_token"] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]['access_token'] == access_token: db.child("users").child(x).update( {"access_token_spotify": access_token_spotify}, user['idToken']) return jsonify({ "message": "Spotify User Login.", "access_token_spotify": access_token_spotify, "admin": True if all_users[x]["admin"] == 1 else False }), 200 return jsonify({ "message": "Spotify problem occured.", "access_token": access_token }), 404
def addSubscribedService(): from index import db, user service = request.json["service"] access_token = request.json["access_token"] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token: db.child("users").child(x).child("services").update( {service: 1}, user['idToken']) return jsonify({"message": "service user updated."}), 200 return jsonify({"message": "user not found"}), 404
def setAutologin(): from index import db, user autologin = request.json["autologin"] access_token = request.json["access_token"] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token: db.child("users").child(x).update({"intra_autologin": autologin}, user['idToken']) return jsonify({"message": "Autologin added."}), 200 return jsonify({"message": "User not found"}), 404
def getUserInformations(): """ permission will give you the informations of a specific user. Obviously you need to give an access token which have the right access to modify the permission of any user.\n @login = login of the user(email).\n @access_token = Token of the user doing the request.\n example of request : http://127.0.0.1:5000/getUserInformations\n access_token=$2b$12$mmML0e8FfPoKsLKyrTidje7lf9erfSu2OkV4NOUV.NuK7IF4z6CoW\n :return: json string will be return. Error: {"error": "404", "message": "Either the access_token doesn't have the right access or your user doesn't exist in our database."} Success: {"success": "200", "message": "Account updated"} """ from index import db, user access_token = request.json["access_token"] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token: return jsonify({"user": all_users[x]}), 200 return jsonify({ "message": "Either the access_token doesn't have the right access or your user " "doesn't exist in our database." }), 404
def getUsers(): """ permission will give you the permissions of a specific user. Obviously you need to give an access token which have the right access to modify the permission of any user.\n @login = login of the user(email).\n @access_token = Token of the user doing the request.\n example of request : http://127.0.0.1:5000/getUsers\n access_token=$2b$12$mmML0e8FfPoKsLKyrTidje7lf9erfSu2OkV4NOUV.NuK7IF4z6CoW\n :return: json string will be return. Error: {"error": "404", "message": "The access token is wrong or the user doesn't have the right access"} Success: {"success": "200", "message": "Account updated"} """ from index import db, user access_token = request.json["access_token"] right_access = 0 # check user who own access_token got admin right all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token and all_users[x][ "admin"] == 1: right_access = 1 break if right_access == 1: return jsonify({"message": "", "users": all_users}), 200 return jsonify({ "message": "The access token is wrong or the user doesn't have the right access" }), 404
def register(): request_json = request.get_json() data = request_json['data'] email = data['email'] password = data['password'] try: all_users = db.child("users").get() for user in all_users.each(): user_val = user.val() user_email = user_val['email'] if user_email == email: raise Exception('user already registered') db.child("users").push(data) except Exception as error: print error return 'OK'
def modifyPermission(): """ modifyPermission will change the permission admin of a specific user given in body args. Obviously you need to give an access token which have the right access to modify the permission of any user.\n @login = login of the user(email).\n @access_token = Token of the user doing the request.\n @admin = new permission that you need to change.\n example of request : http://127.0.0.1:5000/modifyPermission\n [email protected]\n access_token=$2b$12$mmML0e8FfPoKsLKyrTidje7lf9erfSu2OkV4NOUV.NuK7IF4z6CoW\n admin=1\n :return: json string will be return. Error: {"error": "404", "message": "Either the access_token doesn't have the right access or your user doesn't exist in our database."} Success: {"success": "200", "message": "Account updated"} """ from index import db, user login = request.json["login"] access_token = request.json["access_token"] admin = request.json["admin"] right_access = 0 # check user who own access_token got admin right all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token and all_users[x][ "admin"] == 1: right_access = 1 break if right_access == 1: for x in all_users: if all_users[x]["email"] == login: db.child("users").child(x).update({"admin": admin}, user['idToken']) return jsonify({"message": "Account updated"}), 200 return jsonify({ "message": "Either the access_token doesn't have the right access or your user " "doesn't exist in our database." }), 404
def getPlaylistsDeezerUser(): global userId from index import db, user access_token_deezer = request.json["accessTokenDeezer"] access_token = request.json["access_token"] playlists = [] all_users = db.child("users").get(user['idToken']).val() url = "https://api.deezer.com/user/me" print(access_token_deezer) PARAMS = { 'access_token': access_token_deezer, } try: # sending get request and saving the response as response object response = requests.get(url=url, params=PARAMS) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: userId = 0 json_data = json.loads(response.text) userId = json_data['id'] for x in all_users: if all_users[x]['access_token'] == access_token: url = "https://api.deezer.com/user/me/playlists" PARAMS = { 'access_token': access_token_deezer, } try: # sending get request and saving the response as response object response = requests.get(url=url, params=PARAMS) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: json_data = json.loads(response.text) for x in json_data["data"]: tmpDict = { "name": x["title"], "playlist_id": x["id"], } playlists.append(tmpDict) return jsonify(playlists), 200 return jsonify({"message": "Spotify problem occured."}), 404
def isRightToken(token): from index import db, user all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == token: return 1 return 0
def liveScore(): from index import db, user country = request.json["country"] league = request.json["league"] access_token = request.json["access_token"] if isRightToken(access_token) == 0: return jsonify({"message": "Error occurred with your access token."}), 404 league_id = getLeagueByName(country, league) print(league_id) teams = [] # api-endpoint url = "https://apiv2.apifootball.com/" # location given here action = "get_events" APIkey = db.child('services').child('football').child('apikey').get( user['idToken']).val() # defining a params dict for the parameters to be sent to the API PARAMS = { 'action': action, 'league_id': league_id, 'APIkey': APIkey, 'from': datetime.date(datetime.now()), 'to': datetime.date(datetime.now()) } try: # sending get request and saving the response as response object response = requests.get(url=url, params=PARAMS) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: for x in response.json(): if x == "error": print("Error Request: " + response.json()['message']) return jsonify({"message": "Error when fetching live scores."}), 404 if x['match_live'] == '1': tmpDict = { "match_hometeam_name": x['match_hometeam_name'], "match_hometeam_score": x['match_hometeam_score'], "match_awayteam_name": x['match_awayteam_name'], "match_awayteam_score": x['match_awayteam_score'], } teams.append(tmpDict) return jsonify(teams), 200
def getPlaylistsUser(): global userId from index import db, user access_token_spotify = request.json["accessTokenSpotify"] access_token = request.json["access_token"] playlists = [] all_users = db.child("users").get(user['idToken']).val() url = "https://api.spotify.com/v1/me" PARAMS = { 'Authorization': "Bearer " + access_token_spotify, } try: # sending get request and saving the response as response object response = requests.get(url=url, headers=PARAMS) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: userId = response.json()["id"] for x in all_users: if all_users[x]['access_token'] == access_token: url = "https://api.spotify.com/v1/users/" + userId + "/playlists" PARAMS = { 'Authorization': "Bearer " + access_token_spotify, } try: # sending get request and saving the response as response object response = requests.get(url=url, headers=PARAMS) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: for x in response.json()["items"]: tmpDict = { "name": x["name"], "playlist_id": x["id"], "image_url": x["images"][0]["url"], } playlists.append(tmpDict) return jsonify(playlists), 200 return jsonify({"message": "Spotify problem occured."}), 404
def addWidget(): from index import db, user access_token = request.json["access_token"] widget = request.json["widget"] all_users = db.child("users").get(user['idToken']).val() widget["id"] = secrets.token_hex(6) for x in all_users: if all_users[x]["access_token"] == access_token: db.child("users").child(x).child("widgets").push( widget, user['idToken']) return jsonify({ "message": "Widget added.", "id": widget["id"] }), 200 return jsonify({"message": "User not found"}), 404
def delete(): """ delete will delete the user of the database with the loggin information given in information. If the access_token give in body args doesn't have the right access to delete user, our API will return an error. @login = login of the user(email).\n @access_token = Token of the user doing the request\n example of request : http://127.0.0.1:5000/delete\n [email protected]\n access_token=$2b$12$mmML0e8FfPoKsLKyrTidje7lf9erfSu2OkV4NOUV.NuK7IF4z6CoW\n :return: {"error": "404", "message": "Either the access_token doesn't have the right access or your user didn't exist in our database."} Success:{"success": "200", "message": "user deleted."}. br> """ from index import db, user login = request.json["login"] access_token = request.json["access_token"] right_access = 0 all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token and all_users[x][ "admin"] == 1: right_access = 1 break if right_access == 1: for x in all_users: if all_users[x]["email"] == login: db.child("users").child(x).remove(user['idToken']) return jsonify({"message": "user deleted."}), 200 return jsonify({ "message": "Either the access_token doesn't have the right access or your user " "doesn't exist in our database." }), 404
def isRightToken(token): from index import db, user all_users = db.child("users").get(user['idToken']).val() for x in all_users: print("FIREBASE : " + all_users[x]["access_token"]) print("token : " + str(token)) if all_users[x]["access_token"] == token: return 1 return 0
def removeWidget(): from index import db, user access_token = request.json["access_token"] widgetId = request.json["id"] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token: widgets = db.child("users").child(x).child("widgets").get( user['idToken']).val() for y in widgets: if y == "0": continue if widgets[y]["id"] == widgetId: db.child("users").child(x).child("widgets").child( y).remove(user['idToken']) return jsonify({"message": "Widget removed."}), 200 return jsonify({"message": "User or widget not found"}), 404
def getWidgets(): from index import db, user access_token = request.json["access_token"] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token: return jsonify({"widgets": all_users[x]["widgets"]}), 200 return jsonify({"message": "User not found"}), 404
def login(): """ login will login the user and give an access token from our API if the user log correspond in the database. if the loggin information was right, we will add the access token in his database cell as well.\n @login = login of the user(email).\n @password = password of the user.\n example of request : http://127.0.0.1:5000/login\n [email protected]\n password=1p54er7H#\n :return: Error: {"error": "404", "message": "Wrong password or username"} Success: {"success": "200", "access_token": access_token, "is_admin": True} """ from index import db, user login = request.json["login"] password = request.json["password"] print(login) print(password) all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]['email'] == login: if isPasswordValid(all_users[x]['password'], password): access_token = secrets.token_hex(20) db.child("users").child(x).update( {"access_token": access_token}, user['idToken']) admin = all_users[x]["admin"] return jsonify({ "access_token": access_token, "is_admin": True if admin == 1 else False }), 200 else: return jsonify({"message": "Wrong password or username"}), 404 return jsonify({"message": "Wrong password or username"}), 404
def getCompetitions(): """ getCompetitions will return you all the competition that the API have. Format json which are returned : "country_name": x['country_name'] --> name of the country. "league_id": x['league_id'] --> Unique ID of the competition (needed for few other requests) "league_name": x['league_name'], --> name of the league. :rtype: object """ from index import db, user country = "" competitions = [] # api-endpoint url = "https://apiv2.apifootball.com/" # location given here action = "get_leagues" APIkey = db.child('services').child('football').child('apikey').get( user['idToken']).val() # defining a params dict for the parameters to be sent to the API PARAMS = {'action': action, 'country_id': country, 'APIkey': APIkey} try: # sending get request and saving the response as response object response = requests.get(url=url, params=PARAMS) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: for x in response.json(): if x == "error": print("Error Request: " + response.json()['message']) return json.dumps({ "success": 404, "message": "Error when fetching competitions." }) tmpDict = { "country_name": x['country_name'], "league_id": x['league_id'], "league_name": x['league_name'], } competitions.append(tmpDict) return json.dumps(competitions)
def rankLeague(): from index import db, user country = request.json["country"] league = request.json["league"] access_token = request.json["access_token"] if isRightToken(str(access_token)) == 0: return jsonify({"message": "Error occurred with your access token."}), 404 league_id = getLeagueByName(country, league) print(league_id) teams = [] # api-endpoint url = "https://apiv2.apifootball.com/" # location given here action = "get_standings" APIkey = db.child('services').child('football').child('apikey').get( user['idToken']).val() # defining a params dict for the parameters to be sent to the API PARAMS = {'action': action, 'league_id': league_id, 'APIkey': APIkey} try: # sending get request and saving the response as response object response = requests.get(url=url, params=PARAMS) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: for x in response.json(): if x == "error": print("Error Request: " + response.json()['message']) return jsonify( {"message": "Error when fetching rank leagues."}), 404 tmpDict = { "name": x['team_name'], "position": x['overall_league_position'], "match_played": x['overall_league_payed'], "match_winned": x['overall_league_W'], "match_draw": x['overall_league_D'], "match_loosed": x['overall_league_L'] } teams.append(tmpDict) return jsonify(teams), 200
def getpopularRepositories(): from index import db, user access_token = request.json["access_token"] language = request.json["language"] sort = request.json["sort"] order = "desc" repo = [] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]['access_token'] == access_token: url = "https://api.github.com/search/repositories" PARAMS = { 'q': "language:" + language, 'sort': sort, 'order': order, } try: # sending get request and saving the response as response object response = requests.get(url=url, params=PARAMS) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: for x in response.json()["items"]: if x == "error": print("Error Request: " + response.json()['message']) return jsonify({"message": "Error when fetching github repository."}), 404 tmpDict = { "name": x["name"], "stars": x["watchers_count"], "forks": x["forks"] } repo.append(tmpDict) return jsonify(repo), 200 return jsonify({"message": "Github problem occured.", "access_token": access_token}), 404
def getSusbscribedServices(): from index import db, user access_token = request.json["access_token"] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token: return jsonify({ "services": { "football": all_users[x]["services"]['football'], "epitech": all_users[x]["services"]['epitech'], "spotify": all_users[x]["services"]['spotify'], "github": all_users[x]["services"]['github'], "cocktail": all_users[x]["services"]['cocktail'], "open_data": all_users[x]["services"]['open_data'], "deezer": all_users[x]["services"]['deezer'], } }), 200 return jsonify({"message": "user not found"}), 404
def getUserInfo(): from index import db, user access_token_spotify = request.json["accessTokenSpotify"] access_token = request.json["access_token"] infoUser = [] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]['access_token'] == access_token: url = "https://api.spotify.com/v1/me" PARAMS = { 'Authorization': "Bearer " + access_token_spotify, } try: # sending get request and saving the response as response object response = requests.get(url=url, headers=PARAMS) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: infoUser = { "name": response.json()["display_name"], "followers": response.json()["followers"]["total"], "country": response.json()["country"], "userId": response.json()["id"], } return jsonify(infoUser), 200 return jsonify({ "message": "Spotify problem occured.", "access_token": access_token }), 404
def removeSubscribedService(): from index import db, user service = request.json["service"] access_token = request.json["access_token"] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]["access_token"] == access_token: if service == "github" or service == "spotify" or service == "deezer": db.child("users").child(x).update( {"access_token_" + service: 0}, user['idToken']) db.child("users").child(x).child("services").update( {service: 0}, user['idToken']) else: db.child("users").child(x).child("services").update( {service: 0}, user['idToken']) return jsonify({"message": "Service removed."}), 200 return jsonify({"message": "user not found"}), 404
def login(): request_json = request.get_json() data = request_json['data'] email = data['email'] password = data['password'] try: all_users = db.child("users").get() for user in all_users.each(): user_val = user.val() user_email = user_val['email'] user_password = user_val['password'] if user_email == email and user_password == password: verified_user = { 'email': user_email, 'password': user_password, } return jsonify(token=generate_token(verified_user)) else: return jsonify(error=True), 403 except Exception as error: print error return 'OK'
def getuserInfo(): from index import db, user access_token_github = request.json["accessTokenGithub"] access_token = request.json["access_token"] userName = request.json["name"] infoUser = [] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]['access_token'] == access_token: url = "https://api.github.com/users/" + userName try: # sending get request and saving the response as response object response = requests.get(url=url) # If the response was successful, no Exception will be raised response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 else: infoUser = { "name": response.json()["name"], "company": response.json()["company"], "location": response.json()["location"], "bio": response.json()["bio"], "followers": response.json()["followers"], "following": response.json()["following"] } return jsonify(infoUser), 200 return jsonify({"message": "Github problem occured.", "access_token": access_token}), 404
def loginWithGoogle(): """ loginWithGoogle will login the user and give an access token from our API if the user log correspond in the database. if the loggin information was right, we will add the access token in his database cell as well.\n """ from index import db, user login = request.json["email"] access_token_google = request.json["accessToken"] all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]['email'] == login: access_token = secrets.token_hex(20) db.child("users").child(x).update( { "access_token": access_token, "access_token_google": access_token_google }, user['idToken']) return jsonify({ "message": "Google User Login.", "access_token": access_token, "access_token_google": access_token_google, "admin": True if all_users[x]["admin"] == 1 else False }), 200 access_token = secrets.token_hex(20) hashed = makePasswordHash(secrets.token_hex(20)) loginUser = { "email": login, "password": hashed, "admin": 0, "access_token": access_token, "services": { "football": 1, "epitech": 1, "spotify": 0, "deezer": 0, "github": 0, "cocktail": 1, "open_data": 1, }, "widgets": { "0": "0" }, "access_token_fb": 0, "access_token_google": access_token_google, "access_token_spotify": 0, "access_token_deezer": 0, "access_token_github": 0, "intra_autologin": "******" } db.child("users").push(loginUser, user['idToken']) return jsonify({ "message": "Google User registered.", "access_token": access_token, "access_token_google": access_token_google, "admin": False }), 200
def register(): """ register will add the user information to our database.\n @login = login of the user(email).\n @password = password of the user.\n @admin = the admin permission of the user in our platejson. (1 || 0) \n example of request : http://127.0.0.1:5000/register\n [email protected]\n password=1p54er7H#\n admin=1\n :return: Error : {"error": "404", "message": "An account already exists with this email address"} Success : {"success": "200", "message": "user registered."} . """ from index import db, user login = request.json["login"] password = request.json["password"] admin = request.json["admin"] hashed = makePasswordHash(password) all_users = db.child("users").get(user['idToken']).val() for x in all_users: if all_users[x]['email'] == login: return jsonify({ "message": "An account already exists with this email address" }), 404 access_token = secrets.token_hex(20) loginUser = { "email": login, "password": hashed, "admin": admin, "access_token": access_token, "access_token_fb": 0, "access_token_google": 0, "access_token_spotify": 0, "access_token_deezer": 0, "access_token_github": 0, "intra_autologin": "******", "services": { "football": 1, "epitech": 1, "spotify": 0, "deezer": 0, "github": 0, "cocktail": 1, }, "widgets": { "0": "0" } } db.child("users").push(loginUser, user['idToken']) return jsonify({ "message": "User registered.", "access_token": access_token }), 200