Skip to content

Commit

Permalink
Fixed session and add conditional routes
Browse files Browse the repository at this point in the history
  • Loading branch information
MinhPhan8803 committed Nov 28, 2022
1 parent 9c9793d commit aeadb05
Show file tree
Hide file tree
Showing 14 changed files with 51 additions and 25 deletions.
1 change: 1 addition & 0 deletions .github/workflows/pylint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ jobs:
pip install pytest==7.1.3
pip install flask-cors
pip install BeautifulSoup4
pip install Flask-Session2
- name: Analysing the code with pylint
run: |
pylint $(git ls-files '*.py')
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ src/frontend/node_modules
src/backend/.pytest_cache
.pytest_cache
src/backend/__pycache__
src/backend/flask_session

src/frontend/my-app/node_modules
# testing
Expand Down
23 changes: 15 additions & 8 deletions src/backend/app.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
""" Handles routing and HTTP Requests """
import json
import os
import dataclasses
from werkzeug.datastructures import MultiDict
from flask import Flask, request, session
from flask_cors import CORS
from flask_session import Session
from pages.login import Login
from pages.mainpage import MainPage
from pages.userpage import UserPage
from dataholders.mainpage_get import GetRequestType, GetRequestParams

app = Flask(__name__)
app.config["SECRET_KEY"] = os.urandom(24)
CORS(app, resources={r"/*": {"origins": "*"}})
SECRET_KEY = b"xe47Wxcdx86Wxac(mKlxa5xa2,xb3axc6xf1x86Fxc25x94xfc"
SESSION_TYPE = "filesystem"
app.config.from_object(__name__)
Session(app)
CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)


@app.route("/login", methods=["GET", "POST"])
Expand All @@ -27,6 +30,7 @@ def login():
if user_login.login(username, password):
# session object makes User accessible in the backend
session["username"] = username
print(session.get("username"))
return f"welcome {username}", 200
return "User not found, please try again", 401
return "", 400
Expand All @@ -45,15 +49,17 @@ def register():
result = user_login.register(username, email, password, phone)
if not result.status:
return result.message, 400
session["username"] = username
return result.message, 201
return "", 400


@app.route("/user", methods=["GET", "POST"])
def userpage():
"""Handles userpage requests"""
if session.get("username", None) is None:
return "user does not exist", 404
print(session.get("username"))
if session.get("username") is None:
return "user does not exist", 403
name = session.get("username") or ""
page = UserPage(name)
if request.method == "POST":
Expand All @@ -78,7 +84,7 @@ def userpage():
return "success", 201
user = page.get_user(name) # request.method == "GET"
data_dict = dataclasses.asdict(user)
return json.dumps(data_dict), 201
return json.dumps(data_dict), 200


@app.route("/logout")
Expand All @@ -91,8 +97,9 @@ def logout():
@app.route("/api/whoami")
def whoami():
"""Shows whether a user is logged in and returns session username"""
if session.get("username", None) is None:
return "user logged out", 404
print(session.get("username"))
if session.get("username") is None:
return "user logged out", 403
username = session.get("username", "")
return str(username), 201

Expand Down
Binary file modified src/backend/database/database_test.db
Binary file not shown.
14 changes: 8 additions & 6 deletions src/backend/pages/userpage.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,20 @@ def __init__(self, username: str) -> None:
self.user = self.get_user(username)

@use_database
def get_user(self, username: str) -> User:
def get_user(self, query_sql: str) -> User:
"""Return User object based on username"""
query_sql = username
user_query = self.get_user.cursor.execute(
"SELECT u.user_id, u.password, u.email, u.phone \
"SELECT u.user_id, u.username, u.password, u.email, u.phone \
FROM USERS u\
WHERE u.username = ?",
(query_sql,),
WHERE u.username = ? OR u.email = ?",
(
query_sql,
query_sql,
),
).fetchone()
if user_query is None:
return User("", "", "", "", "")
user_id, password, email, phone = user_query
user_id, username, password, email, phone = user_query
return User(user_id, username, password, email, phone)

@use_database
Expand Down
3 changes: 2 additions & 1 deletion src/backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ pytest==7.1.3
pylint==2.15.2
coverage==6.4.4
black==22.8.0
Flask_Cors==3.0.10
Flask_Cors==3.0.10
Flask-Session2==1.3.1
6 changes: 3 additions & 3 deletions src/backend/tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def test_userpage_not_logged_in(client):
assert res.status_code == 404
with app.test_request_context("/user/"):
res = userpage()
assert res[1] == 404
assert res[1] == 403


@use_test
Expand All @@ -301,7 +301,7 @@ def test_userpage_get_request(client):
with app.test_request_context("/user/", method="GET"):
session["username"] = "Mike"
res = userpage()
assert res[1] == 201
assert res[1] == 200
connection = sqlite3.connect("database/database_test.db")
cursor = connection.cursor()
cursor.execute("DELETE FROM Users WHERE username = ?", ("Mike",))
Expand Down Expand Up @@ -372,7 +372,7 @@ def test_whoami():
"""Test whoami returns 404 and 201"""
with app.test_request_context("/api/whoami"):
res = whoami()
assert res[1] == 404
assert res[1] == 403
with app.test_request_context("/api/whoami"):
session["username"] = "Mike"
res = whoami()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export default function getSuggestions(query: string, search: boolean) {
method: 'GET',
url: `http://127.0.0.1:5000/?search=${search}&searchQuery=${query}`,
cancelToken: source.token,
withCredentials: true,
})
.then((res) => {
const newNames: {
Expand Down
3 changes: 3 additions & 0 deletions src/frontend/src/components/user/changeInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export function changeEmail(new_email: string) {
method: 'POST',
url: `${baseURL}`,
data: json,
withCredentials: true,
})
.then((response) => {
console.log(response);
Expand All @@ -35,6 +36,7 @@ export function changePhone(new_phone: string) {
method: 'POST',
url: `${baseURL}`,
data: json,
withCredentials: true,
})
.then((response) => {
console.log(response);
Expand All @@ -51,6 +53,7 @@ export function changePhone(new_phone: string) {
export function logout() {
axios({
url: 'http://127.0.0.1:5000/logout',
withCredentials: true,
})
.then((response) => {
console.log(response);
Expand Down
1 change: 1 addition & 0 deletions src/frontend/src/components/user/getReviewedApts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export default function getReviewedApts(username: string) {
url: `${baseURL}`,
data: json,
cancelToken: source.token,
withCredentials: true,
})
.then((res) => {
setApartments(() => {
Expand Down
1 change: 1 addition & 0 deletions src/frontend/src/components/user/getUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export default function getInfo(username: string) {
method: 'GET',
url: `${baseURL}`,
cancelToken: source.token,
withCredentials: true,
})
.then((res) => {
setUser(() => {
Expand Down
11 changes: 7 additions & 4 deletions src/frontend/src/pages/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,21 @@ export default function Login() {
const navigate = useNavigate();
const [user, setUser] = useState('');
const [password, setPassword] = useState('');
const [res, setRes] = useState('');
const [res, setRes] = useState();

function sendData() {
axios({
method: 'post',
url: 'http://127.0.0.1:5000/login',
withCredentials: true,
data: {
user: user,
password: password,
},
})
.then((response) => {
console.log(response);
navigate('/');
setRes(response.data);
})
.catch((error) => {
if (error.response) {
Expand All @@ -49,6 +50,9 @@ export default function Login() {
width: 310,
margin: '20px auto',
};
if (res === `welcome ${user}`) {
navigate('/');
}
const btnstyle = { margin: '8px 0' };
return (
<Grid>
Expand Down Expand Up @@ -81,7 +85,6 @@ export default function Login() {
style={btnstyle}
onClick={() => {
sendData();
res === '' ? navigate('/') : null;
}}
fullWidth
>
Expand All @@ -93,7 +96,7 @@ export default function Login() {
<Typography>
<Link href="/register">Sign Up</Link>
</Typography>
{res !== '' && (
{res !== undefined && res !== `welcome ${user}` && (
<Typography sx={{ color: '#ff0000' }}>{res}</Typography>
)}
</Paper>
Expand Down
1 change: 1 addition & 0 deletions src/frontend/src/pages/MainPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ function MainPage() {
function checkLoggedIn() {
axios({
url: 'http://127.0.0.1:5000/api/whoami',
withCredentials: true,
})
.then((response) => {
console.log(response);
Expand Down
10 changes: 7 additions & 3 deletions src/frontend/src/pages/Register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default function Register() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [number, setNumber] = useState('');
const [res, setRes] = useState('');
const [res, setRes] = useState();
const paperStyle = {
padding: 20,
height: '70vh',
Expand All @@ -32,6 +32,7 @@ export default function Register() {
axios({
method: 'POST',
url: 'http://127.0.0.1:5000/register',
withCredentials: true,
data: {
username: user,
email: email,
Expand All @@ -41,6 +42,7 @@ export default function Register() {
})
.then((response) => {
console.log(response);
setRes(response.data);
})
.catch((error) => {
if (error.response) {
Expand All @@ -51,6 +53,9 @@ export default function Register() {
}
});
}
if (res === `Register successful, welcome ${user}`) {
navigate('/');
}

return (
<Grid>
Expand Down Expand Up @@ -97,7 +102,6 @@ export default function Register() {
style={btnstyle}
onClick={() => {
sendData();
res === '' ? navigate('/login') : null;
}}
fullWidth
>
Expand All @@ -106,7 +110,7 @@ export default function Register() {
<Typography>
<Link href="/login">Already signed up?</Link>
</Typography>
{res !== '' && (
{res !== undefined && res !== `Register successful, welcome ${user}` && (
<Typography sx={{ color: '#ff0000' }}>{res}</Typography>
)}
</Paper>
Expand Down

3 comments on commit aeadb05

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report
FileStmtsMissCover
app.py1450100%
config.py10100%
decorators.py270100%
dataholders
   apt.py90100%
   mainpage_get.py150100%
   review.py70100%
   user.py80100%
pages
   login.py290100%
   mainpage.py1000100%
   userpage.py530100%
TOTAL3940100%

Tests Skipped Failures Errors Time
49 0 💤 0 ❌ 0 🔥 0.842s ⏱️

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report
FileStmtsMissCover
app.py1450100%
config.py10100%
decorators.py270100%
dataholders
   apt.py90100%
   mainpage_get.py150100%
   review.py70100%
   user.py80100%
pages
   login.py290100%
   mainpage.py1000100%
   userpage.py530100%
TOTAL3940100%

Tests Skipped Failures Errors Time
49 0 💤 0 ❌ 0 🔥 1.225s ⏱️

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report
FileStmtsMissCover
app.py1450100%
config.py10100%
decorators.py270100%
dataholders
   apt.py90100%
   mainpage_get.py150100%
   review.py70100%
   user.py80100%
pages
   login.py290100%
   mainpage.py1000100%
   userpage.py530100%
TOTAL3940100%

Tests Skipped Failures Errors Time
49 0 💤 0 ❌ 0 🔥 1.504s ⏱️

Please sign in to comment.