Skip to content

Commit

Permalink
style: change code style
Browse files Browse the repository at this point in the history
  • Loading branch information
JaishreeJanu committed Mar 4, 2020
1 parent e221e79 commit e1e49d0
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 65 deletions.
74 changes: 53 additions & 21 deletions capstone project/starter/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@


def paginate(request, results):
"""return results in group of 10
10 set of questions shown on each page
Arguments:
request {json} -- json body woth page parameter
results {list} -- results
Returns:
list -- questions on current page
"""
page = request.args.get("page", 1, type=int)
start = (page - 1) * QUESTIONS_PER_PAGE
end = start + QUESTIONS_PER_PAGE
Expand All @@ -23,7 +32,6 @@ def create_app(test_config=None):
app = Flask(__name__)
setup_db(app)
CORS(app)
# db_insert_records()

@app.after_request
def after_request(response):
Expand All @@ -38,8 +46,10 @@ def after_request(response):
@app.route("/actors", methods=["GET"])
@requires_auth("read:actors")
def get_actors(token):
"""
returns all actors if user has 'read:actors' permission
"""gets all actors
if token has 'read:actors' permission
Returns:
json -- success value and list of actors
"""
all_actors = Actor.query.all()
actors = paginate(request, all_actors)
Expand All @@ -52,8 +62,10 @@ def get_actors(token):
@app.route("/movies", methods=["GET"])
@requires_auth("read:movies")
def get_movies(token):
"""
return all movies if user has 'read:movies' permission
"""get all movies
if token has 'read:movies' permission
Returns:
json -- success value and list of movies
"""
all_movies = Movie.query.all()
movies = paginate(request, all_movies)
Expand All @@ -66,8 +78,10 @@ def get_movies(token):
@app.route("/actors", methods=["POST"])
@requires_auth("add:actor")
def add_actor(token):
"""
Adds new actor to the database table if user has 'add:actor' permission
"""Adds a new record in actor db table
if token has 'add:actor' permission
Returns:
json -- success value and id of new record
"""
data = request.get_json()
if not data.get("name"):
Expand All @@ -84,8 +98,10 @@ def add_actor(token):
@app.route("/movies", methods=["POST"])
@requires_auth("add:movie")
def add_movie(token):
"""
Adds new movie to the database table if user has 'add:movie' permission
"""Adds a new record in movie db table
if token contains 'add:movie' permission
Returns:
json -- success value and id of new record
"""
data = request.get_json()
if not data:
Expand All @@ -102,8 +118,12 @@ def add_movie(token):
@app.route("/actors/<int:actor_id>", methods=["PATCH"])
@requires_auth("modify:actor")
def modify_actor(token, actor_id):
"""
modifies the actor details if user has 'modify:actor' permission
"""modifies the actor details with the actor_id,
token must contain 'modify:actor' permission
Arguments:
actor_id {int}: actor id
Returns:
json -- success value and id of updated record
"""
data = request.get_json()
if not data:
Expand All @@ -129,8 +149,12 @@ def modify_actor(token, actor_id):
@app.route("/movies/<int:movie_id>", methods=["PATCH"])
@requires_auth("modify:movie")
def modify_movie(token, movie_id):
"""
modifies the movie details if user has 'modify:movie' permission
"""modifies the movie details with the movie_id,
token must contain 'modify:movie' permission
Arguments:
movie_id {int}: movie id
Returns:
json -- success value and id of updated record
"""
data = request.get_json()
if not data:
Expand All @@ -153,8 +177,12 @@ def modify_movie(token, movie_id):
@app.route("/actors/<int:actor_id>", methods=["DELETE"])
@requires_auth("delete:actor")
def delete_actor(token, actor_id):
"""
deletes actor with actor_id if user has 'delete:actor' permission
"""deletes actor with actor_id,
should contain 'delete:actor' permission
Arguments:
actor_id {int}: actor id
Returns:
json -- success value and id of deleted record
"""
actor = Actor.query.get(actor_id)
if not actor:
Expand All @@ -166,8 +194,12 @@ def delete_actor(token, actor_id):
@app.route("/movies/<int:movie_id>", methods=["DELETE"])
@requires_auth("delete:movie")
def delete_movie(token, movie_id):
"""
deletes movie with movie_id if user has 'delete:movie' permission
"""deletes movie with movie_id,
should contain 'delete:movie' permission
Arguments:
movie_id {int}: movie id
Returns:
json -- success value and id of deleted record
"""
movie = Movie.query.get(movie_id)
if not movie:
Expand Down Expand Up @@ -206,10 +238,10 @@ def resource_not_found(error):
def unprocessable(error):
return (
jsonify(
{
"success": False, "error": 422,
"message": "unprocessable"
}),
{
"success": False, "error": 422, "message": "unprocessable"
}
),
422,
)

Expand Down
20 changes: 6 additions & 14 deletions capstone project/starter/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def get_token_auth_header():
raise AuthError(
{
"code": "invalid_header",
"description": 'Authorization header must start with "Bearer".'
"description": 'Authorization header must start with "Bearer".',
},
401,
)
Expand Down Expand Up @@ -72,8 +72,7 @@ def check_permissions(permission, payload):

if permission not in payload["permissions"]:
raise AuthError(
{"code": "unauthorized", "description": "Permission not found."},
403
{"code": "unauthorized", "description": "Permission not found."}, 403
)
return True

Expand All @@ -89,12 +88,8 @@ def verify_decode_jwt(token):
# Check if Key id is in unverified header
if "kid" not in unverified_header:
raise AuthError(
{
"code": "invalid_header",
"description": "Authorization malformed."
},
401
)
{"code": "invalid_header", "description": "Authorization malformed."}, 401
)

rsa_key = {} # initialize empty private rsa key as dict
for key in jwks["keys"]:
Expand Down Expand Up @@ -153,7 +148,7 @@ def verify_decode_jwt(token):


def requires_auth(permission=""):
""" Authentification Wrapper to decorate Endpoints with
""" Authentification Wrapper to decorate Endpoints
"""

def requires_auth_decorator(f):
Expand All @@ -164,10 +159,7 @@ def wrapper(*args, **kwargs):
payload = verify_decode_jwt(token)
except:
raise AuthError(
{
"code": "unauthorized",
"description": "Permissions not found"
},
{"code": "unauthorized", "description": "Permissions not found"},
401,
)
check_permissions(permission, payload)
Expand Down
24 changes: 10 additions & 14 deletions capstone project/starter/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,33 @@
import json
from datetime import date

# database_name = "bollywood"
# database_path = "postgres:https://{}:{}@{}/{}".format('jaishree','',
# 'localhost:5432',
# database_name)
# database_path = os.environ['DATABASE_URL']
database_path = 'postgres:https://paxwvjtokrycpn:0d70426e3faaa90c7042d'+
'30305d165ac59aab21f3004ebe3a620361f583b1374'+
'@ec2-3-229-210-93.compute-1.amazonaws.com:5432/d20ktjloq6m7p0'

db = SQLAlchemy()

'''
setup_db(app)
binds a flask application and a SQLAlchemy service
'''


def setup_db(app, database_path=database_path):
"""binds a flask application and a SQLAlchemy service
Arguments:
app -- flask app
Keyword Arguments:
database_path -- (default: {database_path})
"""
app.config["SQLALCHEMY_DATABASE_URI"] = database_path
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.app = app
db.init_app(app)
# db.drop_all()
# db.create_all()

# db_insert_records()


def db_insert_records():

"""initialize database tables with few records
"""
# db.create_all()

new_actor = Actor(name='Gisele Budchen', age=40, gender='Female')
new_movie = Movie(title="Lessons", release_date=date.today())

Expand Down
28 changes: 12 additions & 16 deletions capstone project/starter/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@
from sqlalchemy import desc
from datetime import date

assistant_auth = {"Authorization": bearer_tokens["casting_assistant"]}

director_auth_header = {"Authorization": bearer_tokens["casting_director"]}

producer_auth_header = {"Authorization": bearer_tokens["executive_producer"]}
assistant_auth = {
"Authorization": bearer_tokens["casting_assistant"]
}
director_auth_header = {
"Authorization": bearer_tokens["casting_director"]
}
producer_auth_header = {
"Authorization": bearer_tokens["executive_producer"]
}

new_actor = {"name": "ryan gosling", "age": 35, "gender": "Male"}
new_movie = {"title": "Lagaan", "release_date": date.today()}
Expand All @@ -23,17 +27,13 @@ def setUp(self):

self.app = create_app()
self.client = self.app.test_client
# database_name = "bollywood-test"
# database_path = "postgres:https://{}:{}@{}/{}".format('jaishree',\
# 'dabli123','localhost:5432', database_name)
database_path = os.environ["DATABASE_URL"]
setup_db(self.app, database_path)
# binds the app to the current context

with self.app.app_context():
self.db = SQLAlchemy()
self.db.init_app(self.app)
# create all tables
self.db.create_all()

def tearDown(self):
Expand Down Expand Up @@ -125,11 +125,9 @@ def test_modify_actors_400(self):
self.assertEqual(data["message"], "there is no json body")

def test_modify_actors_403(self):
# update an actor , sending assistant header
# update an actor ,sending assistant header(doesn't contain required permissions)
this_actor = {"name": "Priyanka Chopra"}
res = self.client().patch(
"/actors/1", json=this_actor, headers=assistant_auth
)
res = self.client().patch("/actors/1", json=this_actor, headers=assistant_auth)
data = json.loads(res.data)

self.assertEqual(res.status_code, 403)
Expand Down Expand Up @@ -248,9 +246,7 @@ def test_modify_movies_400(self):
def test_modify_movies_403(self):
# update an movie , sending assistant header
this_movie = {"title": "mahabharta"}
res = self.client().patch(
"/movies/1", json=this_movie, headers=assistant_auth
)
res = self.client().patch("/movies/1", json=this_movie, headers=assistant_auth)
data = json.loads(res.data)

self.assertEqual(res.status_code, 403)
Expand Down

0 comments on commit e1e49d0

Please sign in to comment.