Store the user name and password in ".htpasswd", and assume that the password is already encrypted. This time, Basic authentication will be used when accessing the management screen "http: // hogehoge / manage". For the description of "@auth_basic (check)", refer to http://qiita.com/yubessy/items/33789eccb35b659b0b4e. The new one is SAH1 encryption.
Below, the folder structure
/
├── app
│ └── app.py
├── config
│ └─── .htpasswd
└── views
└── manage.j2
Generate a password in advance and store it in .htpasswd. The options of htpasswd are c: new file creation, s: sha1 (encryption format). The user name and password are saved in the above format (user name + ":" + "encrypted format" + encrypted password).
$ htpasswd -csb .htpasswd user password
$ cat .htpasswd
user:{SHA}H9WJLeNwKEfNwYPyPeiv9nuZoxk=
In python, the above is read from the file and compared with the value input by the user, so it is necessary to assemble a character string in the above format with the value input by the user.
The information read from the file did not match in the comparison as it was, probably because there was a line feed code, so trim processing is performed by strip ().
from bottle import route, run, request, auth_basic
import hashlib
import base64
from bottle imp
#Add template path
TEMPLATE_PATH.append("../views")
ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) #Absolute path to the folder where this script is located
def check(username, password):
#Reading server-side settings
f = open(ROOT_PATH + '/../config/.htpasswd', 'r')
auth_check_word = f.readline() #Returns one line of data in a file
f.close()
#Read login information
hs= hashlib.sha1()
hs.update(password.encode("utf-8"))
login_word = username + ":{SHA}" + str(base64.b64encode(hs.digest()).decode("utf-8"))
return auth_check_word.strip() ==login_word.strip()
@route("/manage")
@auth_basic(check)
def manage():
return template('manage.j2')
To be honest, I don't check the best practices around user authentication. This time, we only needed one management screen for the administrator to use, so we have addressed it above. How do other people implement it? Do you have Active Directory etc.?
Recommended Posts