Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed HW2 #5

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
secretkeys.py
*.pyc
74 changes: 72 additions & 2 deletions Auth/AuthAPI.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,77 @@
# Score API here
from flask import Blueprint
from flask import Blueprint, current_app
import sys
from db import db
import jwt

from flask.globals import request
from flask.json import jsonify
from db import *

sys.path.append("../")

auth_api = Blueprint("auth", __name__)

@auth_api.route("/register", methods=["POST"])
def register():

try:
if request.form.get("username") != None:
data = request.form
eugenetaan marked this conversation as resolved.
Show resolved Hide resolved
elif request.args.get("username") != None:
data = request.args
except:
return jsonify({"message": "bad request", "status": "failure"})

username = data["username"]
eugenetaan marked this conversation as resolved.
Show resolved Hide resolved
password = data["passwordHash"]
credentials.append({"username": username, "password": password})

return jsonify({"message": "registered", "status": "success"})


@auth_api.route("/login", methods=["POST"])
def login():

if request.args.get("token") != None:
#check if valid user
login_method = "token"
token = request.args.get("token")
try:
data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=["HS256"])
except:
return jsonify({"status": "failure", "message": "Token Not Valid"})
username = data["userID"]
passwordHash = data["passwordHash"]
else:
login_method = "normal"
if request.form.get("username") != None:
data = request.form
elif request.args.get("username") != None:
data = request.args
username = data["username"]
passwordHash = data["passwordHash"]

# checking if valid user
valid = False
for username_pw_dict in credentials:
if username == username_pw_dict["username"] and passwordHash in username_pw_dict["password"]:
valid = True
break

if not valid:
if login_method == "token":
return jsonify({"status": "failure", "message": "Token Not Valid"})
else:
return jsonify({"status": "failure", "message": "User not found"})

if login_method == "token":
return jsonify({"message": "logged in", "status": "success"})
else:

token = jwt.encode({'userID': username,
'passwordHash': passwordHash
}, current_app.config['SECRET_KEY'], algorithm="HS256")

return jsonify({'token': token, "status": "success"})


57 changes: 56 additions & 1 deletion Profiles/ProfilesAPI.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,62 @@
# Profile API here
from flask import Blueprint
from flask import Blueprint, json, request, jsonify
import sys
from db import db
sys.path.append("../")

profiles_api = Blueprint("profiles", __name__)

@profiles_api.route("/<int:id>", methods=["GET"])
def get_id(id):
try:
if id > len(db) -1 :
return jsonify({"status": "error", "message" : "index out of range"})
return jsonify({"data" : db[id], "status": "success"})
except:
return jsonify({"status": "error"})


@profiles_api.route("/create_profile", methods=["POST"])
eugenetaan marked this conversation as resolved.
Show resolved Hide resolved
def add_new_profile():
try:
data = request.form
new_profile = { "name": data["name"], "scores" : []}
db.append(new_profile)
return jsonify({"added": new_profile, "status": "success"})
except:
return jsonify({"status": "error"})


@profiles_api.route("/<int:id>", methods=["DELETE"])
def delete_profile(id):

if id > len(db) - 1:
return jsonify({"status": "error", "message" : "index out of range"})

del db[id]
return jsonify({"deleted": db[id], "status": "success"})


@profiles_api.route("/<int:id>/score", methods=["GET"])
def get_scores_above_min(id):


if id > len(db) - 1:
return jsonify({"status": "error", "message" : "index out of range"})
data = request.args
scores = db[id]["scores"]

if data.get("minScore") == None:
return jsonify({"data" : scores, "status": "success" })
else:
scores_greater_than_min = list(filter(lambda x : x > int(data["minScore"]), scores))
return jsonify({"data" : scores_greater_than_min, "status": "success" })









Binary file modified Profiles/__pycache__/ProfilesAPI.cpython-38.pyc
Binary file not shown.
Binary file modified __pycache__/db.cpython-38.pyc
Binary file not shown.
10 changes: 10 additions & 0 deletions db.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# Simulated db



db = [{
"name": "Nobel",
"scores": [1, 2, 3, 4, 5]
Expand All @@ -9,3 +12,10 @@
"name": "Hui Hui",
"scores": [9, 29, 34]
}]

credentials = []

auth_secret_key = "425j2jkjdjfk3*38bjb3#*@!)Buibidj2j90$(Tbuiwurbirbjkkjbfkjadkjsf"



183 changes: 183 additions & 0 deletions documentation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
# RHDEV-BE-2-flask Documentation
1. GET /

Get a welcome message.

**Function used**: hello()
**Source**: /**main.py (line 18)**
***
**Parameters**: None
***
**Reponse**: Welcome Message
***
**Example**: /
```
Welcome!
```

2. GET /profiles/\<int:id\>

Get the name and scores associated with that profile based on a given ID.

**Function used**: get_id()
**Source**: /**ProfilesAPI.py (line 10)**
***
**Parameters**:
***
**Response**: JSON object
***
**Example**: /profiles/1
``` json
{
"data": {
"name": "Richard",
"scores": [
5,
4,
3,
2,
1
]
},
"status": "success"
}
```
3. POST /profiles/create_profile

Create a new profile with name only.

**Function used**: add_new_profile()
**Source**: /**ProfilesAPI.py (line 20)**
***
**Parameters**:

name (required)

Name of profile added
***
**Response**: String of Response
***
**Example**: /profiles/create_profile
```json
{
"added": {
"name": "Eugene",
"scores" : [],
},
"Status": "success"
}
```

Otherwise, error will be thrown accordingly

4. DELETE /profiles/\<int:id\>

Delete profile based on id.

**Function used**: delete_profile()
**Source**: /**ProfilesAPI.py (line 31)**
***
**Parameters**:
***
**Response**: String of response
***
**Example**: /profiles/1
```json
{
"deleted": {
"name": "Richard",
"scores": [
5,
4,
3,
2,
1
]
},
"status": "success"
}
```
Otherwise, error will be thrown accordingly

4. GET /profiles/\<int:id\>/score

Get all of the scores of a profile above a specified minimum score.

**Function used**: get_scores_above_min()
**Source**: /**ProfilesAPI.py (line 41)**
***
**Parameters**:

minScore

Get scores of the specified profile based on the given id above minScore. If minScore is not specified, returns all scores.
***
**Response**: List of scores
***
**Example**: /profiles/1/score?minScore=3
```json
{
"data": [
5,
4
],
"status": "success"
}
```
Otherwise, error will be thrown accordingly
6. POST /auth/register

Stores a username and hashedPassword in an array of credentials.

**Function used**: register()
**Source**: /**AuthAPI.py (line 15)**
***
**Parameters**:

username (Required)

Username of user to register

passwordHash (Required)

Password of user
***
**Response**: String of response
***
**Example**: /auth/register?username=eugene&passwordHash=abcdefg123
```json
{
"message": "registered",
"status": "success"
}
```
7. POST /auth/login

Checks if credentials are of registered users.

**Function used**: login()
**Source**: /**AuthAPI.py (line 33)**
***
**Parameters**:

username

Username of user to register

passwordHash

Password of user

token

JWT token to verify login
***
**Response**: If JWT token is not provided, returns JWT token. In other cases, returns string of response
***
**Example**: auth/login?username=eugene&passwordHash=abcdefg123
```json
{
"status": "success",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiJCb2IiLCJwYXNzd29yZEhhc2giOiJ5ZXN3ZWNhbiJ9.iG_2s4dHaiDRdWTDRoawtZ8tv_lW8hb7niAzlTmB8n4",
}
```
14 changes: 13 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
from Auth.AuthAPI import auth_api
from Profiles.ProfilesAPI import profiles_api
from flask import Flask
from db import db
from db import *
import jwt


# Write your flask code here

app = Flask(__name__)

app.config['SECRET_KEY'] = auth_secret_key
app.register_blueprint(profiles_api, url_prefix="/profiles")
app.register_blueprint(auth_api, url_prefix="/auth")

# Endpoints
@app.route("/", methods=["GET"])
def hello():
return "Welcome Message"

# Start the server (developement)
if __name__ == "__main__":
app.run("localhost", port=8080) #Testing on own computer
#app.run("0.0.0.0", port=8080) #Deploying