Specimenrecorder2/server/server/registration.py

70 lines
1.7 KiB
Python

import cherrypy, sqlite3
from cherrypy import HTTPError
required_for_register = ["email", "username", "password", "first_name", "last_name"]
class RegistrationServer(object):
def __init__(self, conf, mkhash):
self.conf = conf
self.mkhash = mkhash
@cherrypy.expose
def index(self):
return open(self.conf["register"]["index"])
@cherrypy.expose
@cherrypy.tools.json_in
def do_register(self):
if(not self.conf["register"]["enabled"]):
raise HTTPError(404, "registration is disabled")
data = cherrypy.request.json
for required in required_for_register:
if not required in data:
raise HTTPError(400, "missing {}".format(required))
username = data["username"]
self.check_username_validity(username)
passwd_hash = self.mkhash(data["password"])
db = sqlite3.connect(self.conf["database"]["users"])
cursor = db.cursor()
cursor.execute("INSERT INTO users("\
"username, passwd_hash, "\
"email, first_name, last_name) "\
"VALUES(?, ?, ?, ?, ?)",
[username, passwd_hash, data["email"],
data["first_name"], data["last_name"])
db.commit()
db.close()
return "registration successful"
@cherrypy.expose
def check_username_validity(self, username):
for i in string.whitespace:
if i in username:
raise HTTPError(400, "username contains whitespace")
for i in "\\\"\b\n\r/":
if i in username:
raise HTTPError(400, "username contains forbidden character")
db = sqlite3.connect(self.conf["database"]["users"])
cursor = db.cursor()
cursor.execute("SELECT uid FROM users WHERE username = ?", [(username)])
if(cursor.fetchone()):
db.close()
raise HTTPError(404, "username already in use")
db.close()
return "username is valid"