Spaces:
Sleeping
Sleeping
Update app/routes/auth.py
Browse files- app/routes/auth.py +34 -6
app/routes/auth.py
CHANGED
|
@@ -47,12 +47,40 @@ async def register(user_data: UserRegister, db: Session = Depends(get_db)):
|
|
| 47 |
status_code=status.HTTP_403_FORBIDDEN,
|
| 48 |
detail="Public registration as Administrator is not permitted. Only existing Administrators can assign this role in User Management.",
|
| 49 |
)
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
existing_user = (
|
| 54 |
db.query(User)
|
| 55 |
-
.filter((User.username ==
|
| 56 |
.first()
|
| 57 |
)
|
| 58 |
if existing_user:
|
|
@@ -61,10 +89,10 @@ async def register(user_data: UserRegister, db: Session = Depends(get_db)):
|
|
| 61 |
detail="Username or email already exists",
|
| 62 |
)
|
| 63 |
|
| 64 |
-
hashed_pw = get_password_hash(
|
| 65 |
new_user = User(
|
| 66 |
-
username=
|
| 67 |
-
email=
|
| 68 |
password_hash=hashed_pw,
|
| 69 |
role=requested_role,
|
| 70 |
)
|
|
|
|
| 47 |
status_code=status.HTTP_403_FORBIDDEN,
|
| 48 |
detail="Public registration as Administrator is not permitted. Only existing Administrators can assign this role in User Management.",
|
| 49 |
)
|
| 50 |
+
username = user_data.username.strip()
|
| 51 |
+
email = user_data.email.strip()
|
| 52 |
+
password = user_data.password
|
| 53 |
+
|
| 54 |
+
# Validate Username
|
| 55 |
+
if len(username) < 3 or len(username) > 20:
|
| 56 |
+
raise HTTPException(
|
| 57 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 58 |
+
detail="Username must be between 3 and 20 characters.",
|
| 59 |
+
)
|
| 60 |
+
import re
|
| 61 |
+
if not re.match(r"^[a-zA-Z0-9_]+$", username):
|
| 62 |
+
raise HTTPException(
|
| 63 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 64 |
+
detail="Username can only contain alphanumeric characters and underscores.",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Validate Email
|
| 68 |
+
if not re.match(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", email):
|
| 69 |
+
raise HTTPException(
|
| 70 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 71 |
+
detail="Please provide a valid email address.",
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Validate Password length
|
| 75 |
+
if len(password) < 6:
|
| 76 |
+
raise HTTPException(
|
| 77 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 78 |
+
detail="Password must be at least 6 characters long.",
|
| 79 |
+
)
|
| 80 |
|
| 81 |
existing_user = (
|
| 82 |
db.query(User)
|
| 83 |
+
.filter((User.username == username) | (User.email == email))
|
| 84 |
.first()
|
| 85 |
)
|
| 86 |
if existing_user:
|
|
|
|
| 89 |
detail="Username or email already exists",
|
| 90 |
)
|
| 91 |
|
| 92 |
+
hashed_pw = get_password_hash(password)
|
| 93 |
new_user = User(
|
| 94 |
+
username=username,
|
| 95 |
+
email=email,
|
| 96 |
password_hash=hashed_pw,
|
| 97 |
role=requested_role,
|
| 98 |
)
|