Spaces:
Sleeping

campuss / src /auth.py
faiz3123's picture
Upload 10 files
746a47e verified
Raw History Blame Contribute Delete
8.7 kB
import streamlit as st
import re
import time
from database import authenticate_user, register_user
def show_login():
"""Display secure login/registration interface"""
st.markdown("## πŸ” Welcome to SkillVerse")
# Create tabs for login and registration
tab1, tab2 = st.tabs(["πŸ”‘ Login", "πŸ“ Register"])
with tab1:
show_login_form()
with tab2:
show_registration_form()
# Demo credentials info
st.markdown("---")
with st.expander("πŸ’‘ Demo Credentials"):
st.markdown("""
**For testing purposes, all existing demo users have the password:** `password123`
**Demo Student Accounts:**
- alex@student.com
- sara@student.com
- mike@student.com
**Demo Faculty Accounts:**
- prof.smith@faculty.com
- dr.jones@faculty.com
**Note:** This is a secure authentication system with password hashing.
""")
def show_login_form():
"""Display login form"""
st.markdown("### πŸ”‘ Login to Your Account")
with st.form("login_form"):
email = st.text_input(
"Email Address",
placeholder="Enter your email address"
)
password = st.text_input(
"Password",
type="password",
placeholder="Enter your password"
)
submit_button = st.form_submit_button("πŸš€ Login", type="primary", use_container_width=True)
if submit_button:
if email and password:
# Basic rate limiting check
if check_rate_limit(email):
user = authenticate_user(email, password)
if user:
# Clear failed attempts on successful login
clear_failed_attempts(email)
# Set session state
st.session_state.authenticated = True
st.session_state.user_role = user['role']
st.session_state.user_id = user['id']
st.session_state.user_name = user['name']
st.success(f"Welcome back, {user['name']}!")
st.rerun()
else:
# Record failed attempt
record_failed_attempt(email)
st.error("❌ Invalid email or password. Please check your credentials and try again.")
else:
st.error("❌ Too many failed attempts. Please wait before trying again.")
else:
st.error("❌ Please enter both email and password.")
def show_registration_form():
"""Display registration form"""
st.markdown("### πŸ“ Create New Account")
with st.form("registration_form"):
col1, col2 = st.columns(2)
with col1:
name = st.text_input(
"Full Name *",
placeholder="Enter your full name"
)
email = st.text_input(
"Email Address *",
placeholder="Enter your email address"
)
role = st.selectbox(
"Role *",
["", "Student", "Faculty"],
help="Select your role in the system"
)
with col2:
password = st.text_input(
"Password *",
type="password",
placeholder="Choose a strong password"
)
confirm_password = st.text_input(
"Confirm Password *",
type="password",
placeholder="Re-enter your password"
)
roll_number = None
if role == "Student":
roll_number = st.number_input(
"Roll Number *",
min_value=1000,
max_value=9999,
value=1000,
help="Enter your student roll number"
)
# Password strength indicator
if password:
strength = check_password_strength(password)
if strength == "Strong":
st.success(f"πŸ”’ Password strength: {strength}")
elif strength == "Medium":
st.warning(f"⚠️ Password strength: {strength}")
else:
st.error(f"❌ Password strength: {strength}")
submit_button = st.form_submit_button("✨ Create Account", type="primary", use_container_width=True)
if submit_button:
# Validation
errors = []
if not name or not email or not password or not role:
errors.append("All required fields must be filled")
if not is_valid_email(email):
errors.append("Please enter a valid email address")
if password != confirm_password:
errors.append("Passwords do not match")
if len(password) < 6:
errors.append("Password must be at least 6 characters long")
if role == "Student" and not roll_number:
errors.append("Roll number is required for students")
if errors:
for error in errors:
st.error(f"❌ {error}")
else:
# Register user
if register_user(email, password, name, role.lower(), roll_number):
st.success("πŸŽ‰ Account created successfully! Please login with your credentials.")
st.balloons()
# Auto-login the user
user = authenticate_user(email, password)
if user:
st.session_state.authenticated = True
st.session_state.user_role = user['role']
st.session_state.user_id = user['id']
st.session_state.user_name = user['name']
st.rerun()
def is_valid_email(email):
"""Validate email format"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def check_password_strength(password):
"""Check password strength"""
if len(password) < 6:
return "Weak"
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_special = any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in password)
strength_score = sum([has_upper, has_lower, has_digit, has_special])
if strength_score >= 3 and len(password) >= 8:
return "Strong"
elif strength_score >= 2 and len(password) >= 6:
return "Medium"
else:
return "Weak"
def check_rate_limit(email):
"""Check if user can attempt login (basic rate limiting)"""
if 'failed_attempts' not in st.session_state:
st.session_state.failed_attempts = {}
if email in st.session_state.failed_attempts:
attempts, last_attempt = st.session_state.failed_attempts[email]
# If more than 5 attempts in last 15 minutes, block
if attempts >= 5 and (time.time() - last_attempt) < 900: # 15 minutes
return False
# If enough time has passed, reset counter
elif (time.time() - last_attempt) > 900:
del st.session_state.failed_attempts[email]
return True
def record_failed_attempt(email):
"""Record a failed login attempt"""
if 'failed_attempts' not in st.session_state:
st.session_state.failed_attempts = {}
if email in st.session_state.failed_attempts:
attempts, _ = st.session_state.failed_attempts[email]
st.session_state.failed_attempts[email] = (attempts + 1, time.time())
else:
st.session_state.failed_attempts[email] = (1, time.time())
def clear_failed_attempts(email):
"""Clear failed attempts for a user after successful login"""
if 'failed_attempts' not in st.session_state:
st.session_state.failed_attempts = {}
if email in st.session_state.failed_attempts:
del st.session_state.failed_attempts[email]
def logout():
"""Clear session state and logout user"""
for key in ['authenticated', 'user_role', 'user_id', 'user_name']:
if key in st.session_state:
del st.session_state[key]
st.success("πŸ‘‹ You have been logged out successfully!")