def editTrack(track): track = request.data requiredFields = [ "trackID", "trackTitle", "trackAlbum", "trackArtist", "trackLength", "trackMediaURL", "trackArt" ] if not all([field in track for field in requiredFields]): raise exceptions.ParseError() else: try: track["trackID"] = uuid.UUID(track["trackID"]) shardKey = track["trackID"].int % 3 if shardKey == 0: affected = trackQueries.edit_track(**track) elif shardKey == 1: affected = trackQueries2.edit_track(**track) elif shardKey == 2: affected = trackQueries3.edit_track(**track) else: raise exceptions.ParseError() if affected is 0: raise exceptions.ParseError("Update Failed") else: result = trackQueries.track_by_id(**track) return result, status.HTTP_200_OK except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT
def filterTrackByID(trackID): shardKey = trackID.int % 3 if request.method == "GET": if shardKey == 0: trackByID = trackQueries.track_by_id(trackID=trackID) elif shardKey == 1: trackByID = trackQueries2.track_by_id(trackID=trackID) elif shardKey == 2: trackByID = trackQueries.track_by_id(trackID=trackID) else: raise exceptions.ParseError() if trackByID is None: raise exceptions.NotFound() return trackByID elif request.method == "DELETE": try: if shardKey == 0: affected = trackQueries.delete_by_id(trackID=trackID) elif shardKey == 1: affected = trackQueries2.delete_by_id(trackID=trackID) elif shardKey == 2: affected = trackQueries3.delete_by_id(trackID=trackID) else: raise exceptions.ParseError() if affected == 0: return {'Error': "TRACK NOT FOUND"}, status.HTTP_404_NOT_FOUND else: return { 'DELETE REQUEST ACCEPTED': str(trackID) }, status.HTTP_202_ACCEPTED except Exception as e: return {'Error': str(e)}, status.HTTP_409_CONFLICT
def createTrack(track): track = request.data requiredFields = [ "trackTitle", "trackAlbum", "trackArtist", "trackLength", "trackMediaURL" ] if not all([field in track for field in requiredFields]): raise exceptions.ParseError() if "trackArt" not in track: track["trackArt"] = "" try: uniqueID = uuid.uuid4() shardKey = uniqueID.int % 3 if shardKey == 0: track['trackID'] = uniqueID trackQueries.create_track(**track) elif shardKey == 1: track['trackID'] = uniqueID trackQueries2.create_track(**track) elif shardKey == 2: track['trackID'] = uniqueID trackQueries3.create_track(**track) else: raise exceptions.ParseError() except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT return track, status.HTTP_201_CREATED
def create_user(username, email, password): # Check if all fields are available if username is None: message = "Missing 'username'" raise exceptions.ParseError(message) if email is None: message = "Missing 'email'" raise exceptions.ParseError(message) if password is None: message = "Missing 'password'" raise exceptions.ParseError(message) # Store fields in a dictionary user = {'username': username, 'email': email, 'password': password} # Encrypt password then register the user into the database try: user['password'] = generate_password_hash(user['password']) user['user_id'] = queries.create_user(**user) except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT # Show the user's data in the API return user, status.HTTP_201_CREATED, {'Location': f'/users/{username}'}
def create_user(user): user = request.data required_fields = ['username', 'full_name', 'password', 'email'] if not all([field in user for field in required_fields]): raise exceptions.ParseError() if (request.data.get('username') == "") or (request.data.get('full_name') == "") or (request.data.get('password') == "") or (request.data.get('email') == ""): raise exceptions.ParseError() try: username = request.data.get('username') full_name = request.data.get('full_name') password_hash = bcrypt.hashpw( base64.b64encode( hashlib.sha256( request.data.get('password').encode('utf-8')).digest()), b'$2b$12$DbmIZ/a5LByoJHgFItyZCe').decode('utf-8') email = request.data.get('email') homeurl = request.data.get('homeurl') queries.create_user(username=username, full_name=full_name, password=password_hash, email=email, homeurl=homeurl) except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT return {user['username']: status.HTTP_201_CREATED}, status.HTTP_201_CREATED
def activate_server(): """ This method runs whole flow of activating a new server """ server_name = str(request.data.get('server_name', '')) if not server_name: raise exceptions.ParseError('No server_name provided?') if not server_manager.check_if_server_exists(server_name): raise exceptions.ParseError( f'Server named {server_name} doesn\'t exist!') if server_manager.is_server_running(): server_manager.stop_server() # activate this server if server_manager.remove_current_version_symlinks(): if not server_manager.create_new_version_symlinks(server_name): raise exceptions.ParseError("Can't create symlinks!") else: raise exceptions.ParseError( "Can't remove symlinks to the current version of the server") if server_manager.start_server(): return {'status': 'server_activated'} else: raise exceptions.ParseError( 'Server was activated but could not be started')
def user_stats(uid): """ Insert and query user events. """ if request.method == 'POST': try: timestamp = parse_timesamp(request.data.get('timestamp', '')) action = parse_action(request.data.get('action', ''), min_action=1, max_action=len(settings.SCORE_VALUES)) data.append(uid, action, timestamp) if settings.CASSANDRA_SUPPORT: cassandra_insert(session, uid, action, timestamp) return {'message': 'ok'} except Exception as ex: raise exceptions.ParseError( detail='{}: {}'.format(ex.__class__.__name__, ex.message)) if request.method == 'GET': try: start = parse_timesamp(request.args.get('start', '')) end = parse_timesamp(request.args.get('end', '')) return data.query(uid, start, end) except Exception as ex: raise exceptions.ParseError( detail='{}: {}'.format(ex.__class__.__name__, ex.message))
def create_playlist(): required_fields = ['playlist_title', 'URL_list', 'username'] user_data = request.data if not all([field in user_data for field in required_fields]): raise exceptions.ParseError() if (request.data.get('playlist_title') == '') or (request.data.get('URL_list') == '') or (request.data.get('username') == ''): raise exceptions.ParseError() user = queries.user_by_id(id=request.data.get('username')) if user: pass else: return { "Status": "User does not exists in user table!" }, status.HTTP_400_BAD_REQUEST if queries.create_playlist( playlist_title=request.data.get('playlist_title'), URL_list=str(request.data.get('URL_list')), username=request.data.get('username'), description=request.data.get('description')): return {"Status": status.HTTP_201_CREATED}, status.HTTP_201_CREATED else: return { "Status": status.HTTP_400_BAD_REQUEST }, status.HTTP_400_BAD_REQUEST
def get_shift(json): shift = json.get('Shift') if shift != None: try: shift = int(shift) return shift except: raise exceptions.ParseError( "Illegal Shift amount: must provide integer") raise exceptions.ParseError("Missing Shift amount") # HTTP status 400
def delete_server(): server_name = str(request.data.get('server_name', '')) if not server_name: raise exceptions.ParseError('No server_name provided?') if not server_manager.check_if_server_exists(server_name): raise exceptions.ParseError( f'Server named {server_name} doesn\'t exist!') # TODO: removing server raise exceptions.NotFound('Not implemented')
def delete_server(server_name): if not server_name: raise exceptions.ParseError('No server_name provided?') if not server_manager.check_if_server_exists(server_name): raise exceptions.ParseError( f'Server named {server_name} doesn\'t exist!') # delete this server if server_manager.delete_server_instance(server_name): return {'status': 'success', 'message': 'Server instance deleted!'} else: raise exceptions.ParseError("Could not delete this server instance!")
def createUser(): if not request.json: raise exceptions.ParseError('Error. No request found.') if not ('username' and 'email' and 'password' in request.json): raise exceptions.ParseError('Error. Parameters incorrect or missing.') username = request.json['username'] email = request.json['email'] hashpass = generate_password_hash(request.json['password'], method='pbkdf2:sha256', salt_length=8) try: queries.create_user(username=username, email=email, hashpass=hashpass) except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT return {'success': 'User account succsefully created.'}, status.HTTP_200_OK
def add_track(UserId, PlaylistId): playlistInfo = request.data playlistInfo['PlaylistId'] = PlaylistId required_fields = ['PlaylistId', 'TrackId'] if not all([field in playlistInfo for field in required_fields]): raise exceptions.ParseError() return add_to_playlist(playlistInfo)
def add_tracks(playlist_id): mandatory_fields = ['track_title'] if not all([field in request.data for field in mandatory_fields]): raise exceptions.ParseError() track_title = request.data.get('track_title', '') db = get_db() try: sqlQry1 = "select track_id from tracks where track_title='%s'" % ( track_title) rs = db.execute(sqlQry1) res = rs.fetchall() rs.close() if len(res) > 0: #print("result is there:",res[0][0]) track_id = res[0][0] sqlQry2 = "insert into playlist_tracks(playlist_id,track_id) values ('%s','%s')" % ( playlist_id, track_id) db.execute(sqlQry2) db.commit() response = Response(status=201) response.headers['location'] = '/playlists/' + playlist_id response.headers['status'] = '201 Created' else: #print("result is not there") return {'message': "Track not found"}, status.HTTP_404_NOT_FOUND except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT return jsonify(res), status.HTTP_201_CREATED
def create_playlists(): mandatory_fields = ['playlist_title', 'user_name', 'track_title'] if not all([field in request.data for field in mandatory_fields]): raise exceptions.ParseError() playlist_title = request.data.get('playlist_title', '') user_name = request.data.get('user_name', '') description = request.data.get('description', '') track_title = request.data.get('track_title', '') db = get_db() try: sqlQry1 = "insert into playlists(user_name,playlist_title,description) values ('%s','%s','%s')" % ( user_name, playlist_title, description) db.execute(sqlQry1) sqlQry2 = "insert into playlist_tracks(playlist_id,track_id) values ((select max(playlist_id) from playlists ),(select track_id from tracks where track_title ='%s'))" % track_title db.execute(sqlQry2) db.commit() response = Response(status=201) response.headers['location'] = '/playlistsbyuser/' + user_name response.headers['status'] = '201 Created' except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT return response, status.HTTP_201_CREATED
def new_playlist(): if request.method =='POST': required=['title', 'creator', 'tracks'] if not all([fields in request.data for fields in required]): raise exceptions.ParseError() temp , q_args = createQuery(request.data) query = "Insert into playlists( creator, title, Description) VALUES(?,?,?);" desc = request.data.get("description") if desc: pass else: q_args.append("NONE") try: query_db(query, q_args) except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT query="SELECT * FROM playlists " +temp qresult=query_db(query, q_args, one=True) id = qresult.get('id') tracks = request.data.get('tracks') query= "INSERT INTO playlist_tracks(playlist_id, track_url) VALUES(?,?);" for x in tracks: try: query_db(query, [id, tracks.get(x)]) except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT return {"MESSAGE": "Playlist Created"}, status.HTTP_201_CREATED else: return {"INFO":"Enter Data For New Playlist"}, status.HTTP_200_OK
def create_tracks(): mandatory_fields = [ 'track_title', 'album_title', 'track_artist', 'track_length', 'media_url' ] if not all([field in request.data for field in mandatory_fields]): raise exceptions.ParseError() try: track_title = request.data.get('track_title', '') album_title = request.data.get('album_title', '') artist = request.data.get('track_artist', '') track_length = request.data.get('track_length', '') media_url = request.data.get('media_url', '') album_url = request.data.get('album_url', '') sqlQry = "insert into tracks(track_title,album_title,track_artist,track_length,media_url,album_url) values ('%s','%s','%s','%s','%s','%s')" % ( track_title, album_title, artist, track_length, media_url, album_url) db = get_db() db.execute(sqlQry) db.commit() response = Response(status=201) response.headers['location'] = '/tracks/' + track_title response.headers['status'] = '201 Created' except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT return response, status.HTTP_201_CREATED
def register(): requestedUser = request.data required_fields = ['username', 'password', 'displayname', 'email'] # Check if required fields exists if not all([field in requestedUser for field in required_fields]): raise exceptions.ParseError() try: # Check if user already Exists in the database checkUser = session.execute( """ SELECT * FROM users WHERE username=%s ALLOW FILTERING """, (requestedUser['username'],) ) if(checkUser.one() is None): requestedUser['homepage'] = "test homepage" addedUser = session.execute( """ INSERT INTO users (username, password, displayname, email, homepage) VALUES (%s, %s, %s, %s, %s) """, (requestedUser['username'], generate_password_hash(requestedUser['password']), requestedUser['displayname'], requestedUser['email'], requestedUser['homepage']) ) return addedUser else: return { 'error': 'username already exists' }, status.HTTP_409_CONFLICT except Exception as e: return { 'error': str(e) }, status.HTTP_409_CONFLICT return status.HTTP_201_CREATED, {'success': 'User Created'}
def auth(): authData = request.data required_fields = ['username', 'password'] # Check if required fields exists if not all([field in authData for field in required_fields]): raise exceptions.ParseError() try: print("in try block") user = session.execute( """ SELECT * FROM users WHERE username=%s ALLOW FILTERING """, (authData['username'],) ) if (check_password_hash(user.one().password, authData['password'])): return {'success': 'valid credentials'}, 200 else: return { 'error': 'invalid credentials' }, 401 except Exception as e: return { 'error': str(e) }, 401
def create_track(track): track = request.data required_fields = ['TrackName', 'Album', 'Artist', 'Length', 'Url'] if not all([field in track for field in required_fields]): raise exceptions.ParseError() try: if not 'Art' in track.keys(): track['Art'] = None TrackId = uuid.uuid4() # UUID object track['TrackID'] = TrackId intTrackId = int(TrackId) # int representation of UUID object shard_key = intTrackId % 3 if shard_key == 0: queries1.create_track(**track) elif shard_key == 1: queries2.create_track(**track) elif shard_key == 2: queries3.create_track(**track) except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT location_url = f'http://localhost:5300/api/v1/tracks?id={TrackId}' return track, status.HTTP_201_CREATED, { "Content-Type": "application/json", "Location": location_url }
def changePassword(): authData = request.data required_fields = ['username', 'new_password'] # Check if required fields exists if not all([field in authData for field in required_fields]): raise exceptions.ParseError() try: user = session.execute( """ SELECT * FROM users where username=%s ALLOW FILTERING """, (authData['username'],) ) if user.one(): session.execute( """ UPDATE users SET password=%s WHERE username=%s """, (generate_password_hash(authData['new_password']), authData['username']) ) print(user) return { 'success': 'password updated' } else: raise exceptions.NotFound() except Exception as e: return { 'error': str(e) }, 401
def create_user(): user = request.data required_fields = ['username', 'password', 'display_name', 'email'] # password is non-hashed at this point if not all([field in user for field in required_fields]): raise exceptions.ParseError() username = user['username'] password = user['password'] display_name = user['display_name'] email = user['email'] try: hashed_password = bcrypt.using(rounds=16).hash(password) # 16 rounds should take ~4 seconds to compute, salts defaulty if 'homepage_url' in user: homepage_url = user['homepage_url'] else: homepage_url = None user['user_id'] = queries.create_user(Username=username,Password=hashed_password, Display_name=display_name, Email=email, Homepage_url=homepage_url) del user['password'] # Do not want response to include hashed password except Exception as e: return { 'error': str(e) }, status.HTTP_409_CONFLICT, { "Content-Type": "application/json" } user_id = user['user_id'] location_url = f'http://localhost:8000/api/v1/users/{user_id}' return user, status.HTTP_201_CREATED, { "Content-Type": "application/json", "Location": location_url }
def parse(self, stream, media_type, **options): data = stream.read().decode('utf-8') try: return json.loads(data) except ValueError as exc: msg = 'JSON parse error - %s' % text_type(exc) raise exceptions.ParseError(msg)
def update_password(username): user = request.data required_fields = ['userUserName', 'userPassword', 'userNewPassword'] if not all([field in user for field in required_fields]): raise exceptions.ParseError() try: get_user_cql = "SELECT * FROM users WHERE userUsername = '******'".format( user['userUserName']) rows = session.execute(get_user_cql) count = 0 for row in rows: data = {} data['userName'] = row.username data['userUserName'] = row.userusername data['userEmail'] = row.useremail data['userPassword'] = row.userpassword count += 1 if count != 0: if check_password_hash(data['userPassword'], user['userPassword']): user['userPassword'] = generate_password_hash( user['userNewPassword']) cql = "UPDATE music.users SET userpassword='******' WHERE userUserName='******'".format( user['userPassword'], user['userUserName']) rows = session.execute(cql) return user, status.HTTP_200_OK return { 'Error': 'Login information invalid' }, status.HTTP_401_UNAUTHORIZED except Exception as e: return {'Error': str(e)}, status.HTTP_409_CONFLICT return {'Error': str(e)}, status.HTTP_409_CONFLICT
def authenticate_user(): request_data = request.data required_fields = ['username', 'password'] if not all([field in request_data for field in required_fields]): raise exceptions.ParseError() username = request_data['username'] password = request_data['password'] # TODO: might return collection even if its just one record db_password = session.execute( """ SELECT password FROM users WHERE username = %(username)s;""", {'username': username}) if bcrypt.verify(password, db_password): # salt is encoded in hashed password return { 'success': 'True' }, status.HTTP_200_OK, { "Content-Type": "application/json" } else: return { 'success': 'False' }, status.HTTP_400_BAD_REQUEST, { "Content-Type": "application/json" }
def createPlaylist(): requestedPlaylist = request.data required_fields = ['title', 'playlist_description', 'creator'] # Check if required fields are met if not all([field in requestedPlaylist for field in required_fields]): raise exceptions.ParseError() try: print("trying to add to db") checkPlaylist = session.execute( """ SELECT * FROM playlists WHERE title=%s ALLOW FILTERING """, (requestedPlaylist["title"], )) print("this is after select execute") playID = uuid.uuid1() session.execute( """ INSERT INTO playlists (guid, title, playlist_description, creator) VALUES (%s, %s, %s, %s) """, (playID, requestedPlaylist['title'], requestedPlaylist['playlist_description'], requestedPlaylist['creator'])) requestedPlaylist['guid'] = str(playID) except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT return requestedPlaylist, status.HTTP_201_CREATED
def editTrack(track): track = request.data requiredFields = [ "trackTitle", "trackAlbum", "trackArtist", "trackLength", "trackMediaURL" ] if not all([field in track for field in requiredFields]): raise exceptions.ParseError() if "trackArt" not in track: track["trackArt"] = "" try: select_track_with = "SELECT * FROM music.tracks WHERE trackTitle='{}' AND trackArtist = '{}' ".format( track["trackTitle"], track["trackArtist"]) rows = session.execute(select_track_with) count = 0 for row in rows: count += 1 if count == 1: insert_track_cql = "INSERT INTO tracks (trackTitle,trackAlbum,trackArtist,trackLength,trackMediaURL,trackArt) VALUES ('{}','{}','{}',{},'{}','{}')".format( track['trackTitle'], track['trackAlbum'], track['trackArtist'], track['trackLength'], track['trackMediaURL'], track['trackArt']) session.execute(insert_track_cql) return track, status.HTTP_200_OK elif count == 0: return {'Error': "Track Doesn't Exists"}, status.HTTP_404_NOT_FOUND except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT return track, status.HTTP_200_OK
def create_user(): # Registers a new user account. user_data = request.get_json() post_fields = {*user_data.keys()} required_fields = {'username', 'email', 'password'} if not required_fields <= post_fields: err = f'Missing fields: {required_fields - post_fields}' raise exceptions.ParseError(err) username = user_data['username'] email = user_data['email'] password = user_data['password'] hashed = generate_password_hash(password, method='pbkdf2:sha256') insert_query = 'INSERT INTO user (username, email, password) VALUES (?, ?, ?)' new_user = (username, email, hashed) db = get_db() try: db.execute(insert_query, new_user) except sqlite3.Error as err: err_string = str(err) if 'UNIQUE' not in err_string: return err_string, status.HTTP_500_INTERNAL_SERVER_ERROR return err_string, status.HTTP_409_CONFLICT db.commit() user_data['password'] = hashed return user_data, status.HTTP_200_OK
def create_user(): user = request.data required_fields = ['userName', 'userUserName', 'userEmail', 'userPassword'] if not all([field in user for field in required_fields]): raise exceptions.ParseError() try: count = 0 user['userPassword'] = generate_password_hash(user['userPassword']) register_cql = "INSERT INTO users (userName, userUserName, userEmail, userPassword) VALUES ('{}','{}','{}','{}')".format( user['userName'], user['userUserName'], user['userEmail'], user['userPassword']) check__userUserName_cql = "Select * From users WHERE userUserName='******'".format( user['userUserName']) check_email_cql = "Select * From users WHERE userEmail='{}'ALLOW FILTERING ".format( user['userEmail']) rows = session.execute(check__userUserName_cql) count = 0 for row in rows: count += 1 rows = session.execute(check_email_cql) for row in rows: count += 1 if count == 0: session.execute(register_cql) else: return { 'Error': 'Username or Email already exists' }, status.HTTP_409_CONFLICT except Exception as e: return {'Error': str(e)}, status.HTTP_409_CONFLICT return user, status.HTTP_201_CREATED
def create_users(): mandatory_fields = ['user_name','password','display_name','email_id'] if not all([field in request.data for field in mandatory_fields]): raise exceptions.ParseError() try: user_name = request.data.get('user_name','') password = request.data.get('password','') hashed_password = generate_password_hash(password) display_name = request.data.get('display_name','') email_id = request.data.get('email_id','') home_url = request.data.get('home_url','') sqlQry = "insert into users(user_name,hashed_password,display_name,email_id,home_url) values ('%s','%s','%s','%s','%s')" %(user_name,hashed_password,display_name,email_id,home_url) db = get_db() db.execute(sqlQry) db.commit() response = Response(status=201) response.headers['location'] = '/users/'+user_name response.headers['status'] = '201 Created' except Exception as e: return { 'error': str(e) }, status.HTTP_409_CONFLICT return response, status.HTTP_201_CREATED