pyg2fa / demo / demo.py

#never ever use this code in your production 
#This is meant to very simplistic example just to show the flow
#Encrypt before saving password and seed in DB 

from bottle import get, post, request
from bottle import route, run
from bottle import redirect
from bottle import response
import pyg2fa

@get('/') 
def login_form():
    return '''<form method="POST" action="/login">
                name:<input name="name"     type="text" />
                password:<input name="password" type="password" />    
                <input type="submit" />         
              </form>'''

@post('/login') 
def login_submit():
    name     = request.forms.get('name')
    password = request.forms.get('password')
    if check_login(name, password):
    	response.set_cookie("g2fa_account", name, secret='somesecretkey')
    	redirect("/otp")
    else:
        return "<p>Login failed</p>"

@get('/otp') 
def otp_form():
	name = request.get_cookie("g2fa_account", secret='somesecretkey')
	if name:
		return '''<form method="POST" action="/otp">
		otp:<input name="otp" type="otp" />
		<input type="submit" />               
		</form>'''
	else:
		redirect("/")
              
@get('/logout') 
def logout():
	name = request.get_cookie(("g2fa_account"), secret='somesecretkey')
	response.delete_cookie("g2fa_account")
	redirect("/")

@post('/otp') 
def otp_form():
   otp     = request.forms.get('otp')
   name = request.get_cookie("g2fa_account", secret='somesecretkey')
   if check_otp(name, otp):
		return "Hello %s. Welcome back. <a href='/logout'>logout</a>" % name
   else:
		return "<p>Login Failed</p>"

def check_login(name, password):
	for a in dummyDB():
		if a['user']==name and a['password'] == password:
			return True
		else:
			return False

def check_otp(name, otp):
	for a in dummyDB():
		if a['user']==name:
			USER_SECRET_INITIAL_OTP_SEED =a['otp_seed']
	if pyg2fa.validate(USER_SECRET_INITIAL_OTP_SEED, int(otp), 4):
		return True
	else:
		return False


def dummyDB():
	return [{"user":"thej","password":"notsafe", "otp_seed":"KKK67SDNLXIOG65U"},{"user":"ram","password":"yeahokay", "otp_seed":""}]

run(host='localhost', port=8080, debug=True)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.