Barra laterale

programmazione:python:autenticazione_utenti_bottle_e_beaker

Autenticazione utenti in Python e Bottle con la libreria Beaker

Autore: Fabio Di Matteo
Ultima revisione: 30/10/2024 - 18:02

Installare Beaker dal gestori di pacchetti della nostra distribuzione oppure con pip.

main.py

#!/usr/bin/python3
 
import  os
from bottle import Bottle,route, run, template, static_file, request,redirect, response,get, post
from login import *
from beaker.middleware import SessionMiddleware
 
global app 
app=Bottle()
 
PORT=8080
 
def start_server():
	run(app , host='0.0.0.0', port=PORT, reloader=True, debug=True)
 
@app.route("/")
def home():
	if (not checkLogin()):
		print("Non autorizzato")
		redirect("/loginform")
	else:
		print("Benvenuto")
		return "<p>Benvenuto</p>"	
 
 
def setup_routing(app):
    app.route('/logout', ['GET', 'POST'], logout) 
    app.route('/dologin', ['GET', 'POST'], dologin)
    app.route('/loginform', ['GET', 'POST'], loginform)  
 
 
setup_routing(app) 
app = SessionMiddleware(app, session_opts)
start_server()

login.py

from bottle import Bottle,route, run, template, static_file, request,redirect, response,get, post
import hashlib
from beaker.middleware import SessionMiddleware
 
users=[
	{"user":"fabio","password":"a53bd0415947807bcb95ceec535820ee","type":"0"},
	{"user":"francesco","password":"0581938f0767a65b373cea80e905c25f","type":"0"}
]
 
session_opts = {
    'session.auto': True,
    'session.type': 'file',
    'session.data_dir': './data/sessions',  
    'session.cookie_expires': 3600
}
 
 
def checkLogin():
	ret=False
	session = request.environ['beaker.session']
	if 'username' in session:
		username= session['username']
		password= session['password']
 
		ret=False
 
		for i in range(0,len(users)):
			if (username ==users[i]["user"] and password == users[i]["password"] ):
				ret=True	
 
	return ret		
 
 
def dologin():
	username = request.forms.get('username')
	password = request.forms.get('password')
	password=hashlib.md5(password.encode("utf-8")).hexdigest()
	print("Login: %s/%s" % (username, password))
 
	session = request.environ['beaker.session']
	session['username'] =username
	session['password'] =password
 
	redirect("/")
 
def loginform():
	return template('login')
 
def logout():
	session = request.environ['beaker.session']
	session.delete()
	redirect("/")

programmazione/python/autenticazione_utenti_bottle_e_beaker.txt · Ultima modifica: 30/10/2024 - 18:13 da Fabio Di Matteo