Skip to content

Commit 86a802e

Browse files
authored
Merge pull request #65 from harshraj22/auth_db
Auth db
2 parents e1364cb + 71ff2a9 commit 86a802e

File tree

7 files changed

+100
-30
lines changed

7 files changed

+100
-30
lines changed

src/auth/main.py

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,58 @@
11
from fastapi import FastAPI, Depends, HTTPException
22
from auth import AuthHandler
3+
import mysql.connector
34
from schemas import AuthDetails
5+
import logging
6+
import requests
47

58

69
app = FastAPI()
710

8-
11+
logger = logging.getLogger(__name__)
912
auth_handler = AuthHandler()
1013
users = [{'username': 'test', 'password': auth_handler.get_password_hash('test')}]
1114

15+
database = mysql.connector.connect(
16+
host ="subscription_db",
17+
user ="root",
18+
passwd ="mypassword",
19+
database = 'DB'
20+
)
21+
cursor_object = database.cursor()
22+
1223
@app.post('/register', status_code=201)
1324
def register(auth_details: AuthDetails):
14-
if any(x['username'] == auth_details.username for x in users):
25+
cursor_object.execute(f"""SELECT * FROM auth where username = '{auth_details.username}'""")
26+
if len(cursor_object.fetchall()) > 0:
1527
raise HTTPException(status_code=400, detail='Username is taken')
1628
hashed_password = auth_handler.get_password_hash(auth_details.password)
17-
users.append({
18-
'username': auth_details.username,
19-
'password': hashed_password
20-
})
29+
cursor_object.execute(f"""INSERT INTO auth VALUES ('{auth_details.username}', '{hashed_password}', 'Free')""")
30+
31+
database.commit()
32+
requests.post(f'http://data_population:8020/sync/', json={'username': auth_details.username})
33+
34+
logger.info(f"User {auth_details.username} registered successfully")
2135
return
2236

2337

2438
@app.post('/login')
2539
def login(auth_details: AuthDetails):
2640
user = None
27-
for x in users:
28-
if x['username'] == auth_details.username:
29-
user = x
30-
break
41+
user_record = cursor_object.execute(f"""SELECT * FROM auth where username = '{auth_details.username}'""")
42+
user_record = cursor_object.fetchall()
43+
44+
if len(user_record) > 0:
45+
user = {
46+
'username': user_record[0][0],
47+
'password': user_record[0][1]
48+
}
49+
50+
logger.debug(f'Entered password: {auth_details.password}, saved password: {user["password"]}')
3151

3252
if (user is None) or (not auth_handler.verify_password(auth_details.password, user['password'])):
3353
raise HTTPException(status_code=401, detail='Invalid username and/or password')
3454
token = auth_handler.encode_token(user['username'])
55+
logger.info(f"User {auth_details.username} logged in successfully")
3556
return { 'token': token }
3657

3758

@@ -42,4 +63,5 @@ def login(auth_details: AuthDetails):
4263

4364
@app.get('/protected')
4465
def protected(username=Depends(auth_handler.auth_wrapper)):
45-
return { 'name': username }
66+
logger.info(f"User {username} accessed protected route")
67+
return { 'name': username }

src/auth/requirements.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
PyJWT
2+
mysql-connector-python==8.0.32
23
passlib
34
bcrypt
45
fastapi
5-
uvicorn
6+
uvicorn
7+
requests

src/data_population/Dockerfile

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ RUN pip install -r requirements.txt
77
#COPY app.py /app.py
88
ADD . /app
99
WORKDIR /app
10+
EXPOSE 8020
1011

11-
12-
CMD ["python3", "-u", "populate.py"]
12+
# CMD ["python3", "-u", "populate.py"]
13+
CMD ["uvicorn", "populate:app", "--reload", "--host", "0.0.0.0", "--port", "8020"]

src/data_population/populate.py

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@
22
import redis
33
import mysql.connector
44
import logging
5+
from fastapi import FastAPI
6+
from pydantic import BaseModel
7+
import requests
8+
9+
10+
class Username(BaseModel):
11+
username: str
512

613

714
logger = logging.getLogger(__name__)
@@ -15,22 +22,41 @@
1522
database = 'DB'
1623
)
1724

25+
app = FastAPI()
26+
1827
r = redis.StrictRedis(host='redis', port=6379, decode_responses=True, password="")
1928
ALLOWED_PREFIX = 'allowed' # max number of requests allowed per WINDOW_LENGTH
2029

2130
# preparing a cursor object
2231
cursor_object = database.cursor()
23-
user_record = """SELECT * FROM subscription_details """
24-
records = cursor_object.execute(user_record)
25-
result = cursor_object.fetchall()
2632

27-
# >>> print(result)
28-
# [('free_user', 'Free', 10, 1), ('basic_user', 'Basic', 100, 15), ('advanced_user', 'Advanced', 1000, 60), ('test', 'Advanced', 1000, 60)]
33+
@app.post('/sync', status_code=200)
34+
def sync(username: Username):
35+
print(f'Syncing {username} to redis')
36+
user_record = f"""SELECT * FROM subscription_details where username = '{username.username}'"""
37+
print(user_record)
38+
cursor_object.execute(user_record)
39+
result = cursor_object.fetchall()
40+
41+
for username, subscription_tier, request_limit, retention_period in result:
42+
r.set(f'{ALLOWED_PREFIX}-{username}', request_limit)
43+
44+
45+
@app.get('/sync_all', status_code=200)
46+
def sync_all():
47+
user_record = """SELECT * FROM subscription_details """
48+
records = cursor_object.execute(user_record)
49+
result = cursor_object.fetchall()
50+
51+
# >>> print(result)
52+
# [('free_user', 'Free', 10, 1), ('basic_user', 'Basic', 100, 15), ('advanced_user', 'Advanced', 1000, 60), ('test', 'Advanced', 1000, 60)]
53+
54+
logger.debug(result)
2955

30-
logger.debug(result)
31-
database.close()
56+
for username, subscription_tier, request_limit, retention_period in result:
57+
r.set(f'{ALLOWED_PREFIX}-{username}', request_limit)
3258

33-
for username, subscription_tier, request_limit, retention_period in result:
34-
r.set(f'{ALLOWED_PREFIX}-{username}', request_limit)
59+
# r.close()
60+
if __name__ == '__main__':
61+
requests.get('http://data_population:8020/sync_all/')
3562

36-
r.close()
Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
11
mysql-connector-python==8.0.32
2-
redis==4.3.3
2+
redis==4.3.3
3+
fastapi
4+
uvicorn
5+
requests

src/frontend/main_page.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,22 @@
99
st.session_state['token'] = None
1010

1111
if st.session_state.token is None:
12+
# Registration form
13+
with st.form('Register'):
14+
username = st.text_input('Username')
15+
password = st.text_input('Password', type='password')
16+
confirm_password = st.text_input('Confirm Password', type='password')
17+
register = st.form_submit_button('Register')
18+
if register:
19+
if password == confirm_password:
20+
r = requests.post('http://auth:8019/register', json={'username': username, 'password': password})
21+
if r.status_code == 201:
22+
st.success('Registration successful')
23+
else:
24+
st.error('Registration failed')
25+
else:
26+
st.error('Passwords do not match')
27+
1228
with st.form('Authenticate'):
1329
username = st.text_input('Username')
1430
password = st.text_input('Password', type='password')

src/subscription_db/schema.sql

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ CREATE TABLE `subscription` (
1414
DROP TABLE IF EXISTS `auth`;
1515
CREATE TABLE auth (
1616
`username` VARCHAR(20) PRIMARY KEY,
17-
`password` VARCHAR(20) NOT NULL,
17+
`password` VARCHAR(80) NOT NULL,
1818
`subscription_tier` varchar(10) NOT NULL,
1919
FOREIGN KEY (`subscription_tier`) REFERENCES `subscription`(`subscription_tier`)
2020
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
@@ -31,10 +31,10 @@ VALUES
3131

3232
INSERT INTO `auth` (`username`, `password`, `subscription_tier`)
3333
VALUES
34-
('free_user', 'free', 'Free'),
35-
('basic_user', 'basic', 'Basic'),
36-
('advanced_user', 'advanced', 'Advanced'),
37-
('test', 'test', 'Advanced');
34+
('free_user', '$2b$12$Zyc0kpMpoqAefW9GHzotku4zxqru.2ihF.xdfuzAc6LmiRTURzcbm', 'Free'), -- password: 'free'
35+
('basic_user', '$2b$12$GdyyqYJ0PumKjP3RmEJJceD78xbAvoAXLS5i70kHFmelbei8x9ddG', 'Basic'), -- password: 'basic'
36+
('advanced_user', '$2b$12$bjNu058XT2R0dEgUi0Usn.hw4xbeahN/lmM1w3t3W8pLV9r70MXxu', 'Advanced'), -- password: 'advanced'
37+
('test', '$2b$12$1w6qLVssMOpw4vFoVerFQunrZnlQT1YZUW7.sErHVXSSGJPtvEvte', 'Advanced'); -- password: 'test'
3838

3939

4040
CREATE VIEW `subscription_details` AS SELECT a.username, s.subscription_tier, s.request_limit, s.retention_period FROM auth a INNER JOIN subscription s ON a.subscription_tier = s.subscription_tier;

0 commit comments

Comments
 (0)