Skip to content

Commit

Permalink
Merge pull request #79 from harshraj22/registration_fix
Browse files Browse the repository at this point in the history
Registration fix
  • Loading branch information
harshraj22 authored May 15, 2023
2 parents 151acaa + 9bf5fe7 commit f6e283c
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 27 deletions.
3 changes: 2 additions & 1 deletion src/auth/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ def register(auth_details: AuthDetails):
cursor_object.execute(f"""INSERT INTO auth VALUES ('{auth_details.username}', '{hashed_password}', 'Free')""")

database.commit()
requests.post(f'http://data_population:8020/sync/', json={'username': auth_details.username})
response = requests.post(f'http://data_population:8020/sync/', json={'username': auth_details.username})
print(f'Response from data_population for syncing data: {response.status_code}')

logger.info(f"User {auth_details.username} registered successfully")
return
Expand Down
40 changes: 29 additions & 11 deletions src/data_population/populate.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,36 +15,51 @@ class Username(BaseModel):
logger.setLevel(logging.DEBUG)


database = mysql.connector.connect(
host ="subscription_db",
user ="root",
passwd ="mypassword",
database = 'DB'
)

app = FastAPI()

r = redis.StrictRedis(host='redis', port=6379, decode_responses=True, password="")
ALLOWED_PREFIX = 'allowed' # max number of requests allowed per WINDOW_LENGTH

# preparing a cursor object
cursor_object = database.cursor()

@app.post('/sync', status_code=200)
def sync(username: Username):
logger.info(f'Syncing {username} to redis')
database = mysql.connector.connect(
host ="subscription_db",
user ="root",
passwd ="mypassword",
database = 'DB'
)

# preparing a cursor object
cursor_object = database.cursor()

print(f'Syncing {username} to redis')
user_record = f"""SELECT * FROM subscription_details where username = '{username.username}'"""
logger.info('User Record:', user_record)
print('User Record:', user_record)
cursor_object.execute(user_record)
result = cursor_object.fetchall()

for username, subscription_tier, request_limit, retention_period in result:
r.set(f'{ALLOWED_PREFIX}-{username}', request_limit)


cursor_object.close()
database.close()

@app.on_event("startup")
@app.get('/sync_all', status_code=200)
def sync_all():

database = mysql.connector.connect(
host ="subscription_db",
user ="root",
passwd ="mypassword",
database = 'DB'
)

# preparing a cursor object
cursor_object = database.cursor()

user_record = """SELECT * FROM subscription_details """
records = cursor_object.execute(user_record)
result = cursor_object.fetchall()
Expand All @@ -57,6 +72,9 @@ def sync_all():
for username, subscription_tier, request_limit, retention_period in result:
r.set(f'{ALLOWED_PREFIX}-{username}', request_limit)

cursor_object.close()
database.close()

@app.get('/healthcheck', status_code=200)
def healthcheck():
return 'OK'
Expand Down
53 changes: 53 additions & 0 deletions src/frontend/locustfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import logging
import numpy as np
import base64
import requests
from locust import HttpUser, task, between

API_URL = "http://0.0.0.0:8001/submit"
LOGIN_URL = "http://0.0.0.0:8019/login"
USERNAME = "test"
PASSWORD = "test"

logging.basicConfig(level=logging.INFO)

def get_auth_token():
"""
Retrieves authentication token by sending a POST request to login API.
Returns:
str: Authentication token.
"""
data = {'username': USERNAME, 'password': PASSWORD}
response = requests.post(LOGIN_URL, json=data)
response.raise_for_status()
auth_token = response.json().get('token')
logging.info(f'Status_code: {response.status_code}, auth token: {auth_token}')
return auth_token

img = np.random.rand(256, 256, 3)
img = base64.b64encode(img).decode("utf-8")

logging.info(f"curl -X POST -H 'Content-Type: application/json' -d '{{'username': '{USERNAME}', 'password': '{PASSWORD}'}}' {LOGIN_URL}")
auth_token = get_auth_token()

headers = {'User-Agent': 'Mozilla/5.0', 'Authorization': f'Bearer {auth_token}'}
payload = {'img1': img, 'img2': img}

def sync_health_check():
"""
Sends a POST request to the API endpoint to perform a health check.
"""
session = requests.Session()
response = session.post(API_URL, headers=headers, files=payload)
logging.info(f'Server responded with {response}')

class QuickstartUser(HttpUser):
wait_time = between(1, 2)

@task
def check_api_endpoint(self):
"""
Sends a POST request to the API endpoint using Locust client.
"""
self.client.post("/submit", headers=headers, files=payload)
27 changes: 14 additions & 13 deletions src/frontend/main_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,21 @@

if st.session_state.token is None:
# Registration form
with st.form('Register'):
username = st.text_input('Username')
password = st.text_input('Password', type='password')
confirm_password = st.text_input('Confirm Password', type='password')
register = st.form_submit_button('Register')
if register:
if password == confirm_password:
r = requests.post('http://auth:8019/register', json={'username': username, 'password': password})
if r.status_code == 201:
st.success('Registration successful')
with st.expander('Register New User'):
with st.form('Register'):
username = st.text_input('Username')
password = st.text_input('Password', type='password')
confirm_password = st.text_input('Confirm Password', type='password')
register = st.form_submit_button('Register')
if register:
if password == confirm_password:
r = requests.post('http://auth:8019/register', json={'username': username, 'password': password})
if r.status_code == 201:
st.success('Registration successful')
else:
st.error('Registration failed')
else:
st.error('Registration failed')
else:
st.error('Passwords do not match')
st.error('Passwords do not match')

with st.form('Authenticate'):
username = st.text_input('Username')
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
streamlit==1.10.0
streamlit==1.22.0
3 changes: 2 additions & 1 deletion test/integration_test/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
class TestImageSimilarityWorkflow(unittest.TestCase):

def setUp(self):
r = requests.post('http://auth:8019/register', json={'username': 'free_user_007', 'password': 'free'})
# Authenticate and store the auth token for later use
r = requests.post('http://auth:8019/login', json={'username': 'free_user', 'password': 'free'})
r = requests.post('http://auth:8019/login', json={'username': 'free_user_007', 'password': 'free'})
self.assertEqual(r.status_code, 200)
self.token = r.json()['token']

Expand Down

0 comments on commit f6e283c

Please sign in to comment.