Junior — Middle
How can you implement a user authentication system?
sobes.tech AI
Answer from AI
The user authentication system can be implemented as follows:
- Storing user data — logins and password hashes are stored in a database or other storage.
- User registration — during registration, the password is hashed using a secure algorithm (e.g., bcrypt) and stored.
- Authentication — during login, the user enters their login and password, the system hashes the entered password and compares it with the stored hash.
- Sessions or tokens — after successful authentication, a session or JWT token is created to identify the user in subsequent requests.
Example in Python using the bcrypt library:
import bcrypt
# Hashing the password during registration
password = b"user_password"
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# Checking the password during login
entered_password = b"user_password"
if bcrypt.checkpw(entered_password, hashed):
print("Authentication successful")
else:
print("Incorrect password")
For a complete system, session handling, attack protection, attempt limiting, etc., are usually added.