Sobes.tech
Junior — Middle

How can you implement a user authentication and authorization mechanism in an application?

sobes.tech AI

Answer from AI

To implement user authentication and authorization in a Python application, the following approaches are often used:

  1. Authentication — verifying the user's identity. Usually implemented through checking login and password stored in a database. Passwords should be stored as hashes (for example, using bcrypt).

  2. Authorization — defining user rights after successful authentication. Roles (e.g., admin, user) can be implemented, and access to certain resources can be checked.

Example using Flask and Flask-Login:

from flask import Flask, request, redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app = Flask(__name__)
app.secret_key = 'secret_key'

login_manager = LoginManager()
login_manager.init_app(app)

# Example user class
class User(UserMixin):
    def __init__(self, id):
        self.id = id

# Load user by id
@login_manager.user_loader
def load_user(user_id):
    return User(user_id)  # Usually a database query here

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    # Check user and password (e.g., database query)
    if username == 'admin' and password == 'password':
        user = User(id=1)
        login_user(user)
        return redirect(url_for('protected'))
    return 'Invalid credentials', 401

@app.route('/protected')
@login_required
def protected():
    return f'Hello, user {current_user.id}!'

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return 'You have logged out'

if __name__ == '__main__':
    app.run()

Thus, authentication verifies the user, and authorization restricts access to resources based on their rights.