Beispiel #1
0
    def create(self, data):

        self.username = data.get("username")
        self.password = pbkdf2_sha256.hash(data.get("password"))
        self.admin = bool(data.get("admin"))

        if self.save():
            return self
Beispiel #2
0
 def validate_password(cls, password):
     #cls is used instead of self, see PEP-8
     print('verify_password with {0}, {1}'.format(password,cls.password))
     print(pbkdf2_sha256.hash(password))
     try:
 	    if pbkdf2_sha256.verify(password,cls.password):
 	        return True
 	    else:
 	        return False
     except Exception as e:
         print('Error verifying password: {0}'.format(e))
         return False
Beispiel #3
0
 def generate_hash(password):
     return sha256.hash(password)
        ini = iniparse.RawConfigParser()
        if os.path.isfile(ini_fn):
            ini.read(ini_fn)
            waptserver_port = ini.get('options','waptserver_port','%s' % sport)
            application_root = ini.get('options','application_root',instance)
            del ini
        else:
            while sport in ports:
                sport +=1
            ports.append(sport)

            application_root=instance
            secret_key=''.join(random.SystemRandom().choice(string.letters + string.digits) for _ in range(64))
            server_uuid=str(uuid.uuid1())
            wapt_password=pbkdf2_sha256.hash('password'.encode('utf8'))
            waptserver_config = Template(waptserver_template).render(**locals())
            open(ini_fn,'wb').write(waptserver_config)

        nginx_fn = '/opt/wapt/conf/wapt.d/%s.conf' % application_root
        if not os.path.isdir('/opt/wapt/conf/wapt.d'):
            os.makedirs('/opt/wapt/conf/wapt.d')
        conf = Template(instance_template).render(**locals())
        codecs.open(nginx_fn,'wb',encoding='utf8').write(conf)

        nginx_fn = '/etc/nginx/sites-available/wapt.conf'
        nginx_conf = Template(nginx_template).render(**locals())
        codecs.open(nginx_fn,'wb',encoding='utf8').write(nginx_conf)

        systemd_fn = '/usr/lib/systemd/system/waptserver-%s.service' % application_root
        if not os.path.isdir('/usr/lib/systemd/system'):
Beispiel #5
0
from passlib.hash import pbkdf2_sha256

hash1 = pbkdf2_sha256.hash("password1")
print(hash1)

hash2 = pbkdf2_sha256.hash("password1")
print(hash2)

print(len(hash1))

print(pbkdf2_sha256.verify("password1", hash1))
Beispiel #6
0
 def get_hash(pw):
     return pbkdf2_sha256.hash(pw)
Beispiel #7
0
from run import db
from models.account import Account

import sqlalchemy
import os, uuid, base62
from passlib.hash import pbkdf2_sha256 as sha256

# add Account
account = Account()
account.id = "user"
account.pw = sha256.hash("user")
account.level = "U"
account.active = "Y"

db.session.add(account)
db.session.commit()
Beispiel #8
0
import random
from passlib.hash import pbkdf2_sha256

from model import db, Donor, Donation, User

db.connect()

# This line will allow you "upgrade" an existing database by
# dropping all existing tables from it.
db.drop_tables([Donor, Donation, User])

db.create_tables([Donor, Donation, User])

alice = Donor(name="Alice")
alice.save()

bob = Donor(name="Bob")
bob.save()

charlie = Donor(name="Charlie")
charlie.save()

donors = [alice, bob, charlie]

for x in range(30):
    Donation(donor=random.choice(donors), value=random.randint(100,
                                                               10000)).save()

User(name="admin", password=pbkdf2_sha256.hash("password")).save()
User(name="sophieloaphie", password=pbkdf2_sha256.hash("supersecret")).save()
Beispiel #9
0
 def hash_password(self, password):
     try:
         return pbkdf2_sha256.hash(password)
     except Exception as e:
         print('Erro ao criptografar senha %s' % e)
 def __init__(self, nome, sobrenome, email, senha):
     self.__sobrenome = sobrenome
     self.__nome = nome
     self.__email = email
     self.__senha = cryp.hash(senha, rounds=20000, salt_size=16)
Beispiel #11
0
 def __init__(self, username, email, password, description=None, admin=None):
     self.username = username
     self.email = email
     self.password = pbkdf2_sha256.hash(password)
     self.description = description
     self.admin = admin
Beispiel #12
0
def change_admin_password(newpassword):
    new_hash = pbkdf2_sha256.hash(newpassword.encode('utf8'))
    rewrite_config_item(app.config['CONFIG_FILE'],'options', 'wapt_password', new_hash)
    app.conf['wapt_password'] = new_hash
Beispiel #13
0
 def generate_hash(password):
   """
   パスワードをハッシュ化する
     :param password: ハッシュ化するパスワード
   """
   return sha256.hash(password)
Beispiel #14
0
"""
Scripts to run to set up our database
"""
from datetime import datetime
from model import db, User, Task
from passlib.hash import pbkdf2_sha256


# Create the database tables for our model
db.connect()
db.drop_tables([User, Task])
db.create_tables([User, Task])

Task(name="Do the laundry.").save()
Task(name="Do the dishes.", performed=datetime.now()).save()
User(name="admin", password=pbkdf2_sha256.hash('password')).save()
User(name='bob', password=pbkdf2_sha256.hash('bobbob')).save()
Beispiel #15
0
from passlib.hash import pbkdf2_sha256

password = '******'

hash_pw = pbkdf2_sha256.hash(password)

print(pbkdf2_sha256.verify(password, hash_pw))
Beispiel #16
0
def encrypt_password(password):
    encrypted_password = pbkdf2_sha256.hash(password)
    return encrypted_password
Beispiel #17
0
 def encrypt(cls, value: str):
     crypt = pbkdf2_sha256.hash(str(value))
     return crypt
Beispiel #18
0
 def __init__(self, username: str, password: str):
     self.username = username
     self.password_hash = sha256.hash(password)
Beispiel #19
0
 def on_model_change(self, _form, model, is_created):
     password = model.get('password')
     model['password'] = sha256.hash(password)
     reccourse = model.get('reccourse')
     print(reccourse)
     return model
Beispiel #20
0
 def set_password(self, password):
     self.password = pbkdf2_sha256.hash(password)
Beispiel #21
0
def password_update(user_id, new_password):
    user.update_one({"_id": ObjectId(user_id)},
                    {"$set": {
                        "password": p256.hash(new_password)
                    }})
Beispiel #22
0
def hash_text(text: str) -> str:
    hashed_text = pbkdf2_sha256.hash(text)
    return hashed_text
Beispiel #23
0
 def __init__(self, id, senha, falhas):
     self.__id = id
     self.__senha = cryp.hash(senha, round=20000, salt_size=16)
     self.__senha = falhas
Beispiel #24
0
def Crypter(args):
    if args.encrypt == 'pbkdf2_sha256':
        return pbkdf2_sha256.hash(args.text)
    elif args.encrypt == 'oracle11':
        return oracle11.hash(args.text)
    elif args.encrypt == 'argon2':
        return argon2.hash(args.text)
    elif args.encrypt == 'bcrypt':
        return bcrypt.hash(args.text)
    elif args.encrypt == 'bcrypt_sha256':
        return bcrypt_sha256.hash(args.text)
    elif args.encrypt == 'cisco_asa':
        return cisco_asa.hash(args.text)
    elif args.encrypt == 'cisco_pix':
        return cisco_pix.hash(args.text)
    elif args.encrypt == 'cisco_type7':
        return cisco_type7.hash(args.text)
    elif args.encrypt == 'bigcrypt':
        return bigcrypt.hash(args.text)
    elif args.encrypt == 'bsdi_crypt':
        return bsdi_crypt.hash(args.text)
    elif args.encrypt == 'des_crypt':
        return des_crypt.hash(args.text)
    elif args.encrypt == 'hex_md4':
        return hex_md4.hash(args.text)
    elif args.encrypt == 'hex_md5':
        return hex_md5.hash(args.text)
    elif args.encrypt == 'hex_sha1':
        return hex_sha1.hash(args.text)
    elif args.encrypt == 'hex_sha256':
        return hex_sha256.hash(args.text)
    elif args.encrypt == 'hex_sha512':
        return hex_sha512.hash(args.text)
    elif args.encrypt == 'django_bcrypt':
        return django_bcrypt.hash(args.text)
    elif args.encrypt == 'django_disabled':
        return django_disabled.hash(args.text)
    elif args.encrypt == 'django_bcrypt_sha256':
        return django_bcrypt_sha256.hash(args.text)
    elif args.encrypt == 'django_des_crypt':
        return django_des_crypt.hash(args.text)
    elif args.encrypt == 'django_pbkdf2_sha1':
        return django_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'django_pbkdf2_sha256':
        return django_pbkdf2_sha256.hash(args.text)
    elif args.encrypt == 'django_salted_md5':
        return django_salted_md5.hash(args.text)
    elif args.encrypt == 'django_salted_sha1':
        return django_salted_sha1.hash(args.text)
    elif args.encrypt == 'fshp':
        return fshp.hash(args.text)
    elif args.encrypt == 'ldap_bcrypt':
        return ldap_bcrypt.hash(args.text)
    elif args.encrypt == 'ldap_md5':
        return ldap_md5.hash(args.text)
    elif args.encrypt == 'ldap_plaintext':
        return ldap_plaintext.hash(args.text)
    elif args.encrypt == 'ldap_sha1':
        return ldap_sha1.hash(args.text)
    elif args.encrypt == 'ldap_bsdi_crypt':
        return ldap_bsdi_crypt.hash(args.text)
    elif args.encrypt == 'ldap_hex_md5':
        return ldap_hex_md5.hash(args.text)
    elif args.encrypt == 'ldap_hex_sha1':
        return ldap_hex_sha1.hash(args.text)
    elif args.encrypt == 'ldap_md5_crypt':
        return ldap_md5_crypt.hash(args.text)
    elif args.encrypt == 'ldap_pbkdf2_sha1':
        return ldap_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'ldap_pbkdf2_sha256':
        return ldap_pbkdf2_sha256.hash(args.text)
    elif args.encrypt == 'ldap_pbkdf2_sha512':
        return ldap_pbkdf2_sha512.hash(args.text)
    elif args.encrypt == 'ldap_salted_md5':
        return ldap_salted_md5.hash(args.text)
    elif args.encrypt == 'ldap_salted_sha1':
        return ldap_salted_sha1.hash(args.text)
    elif args.encrypt == 'ldap_sha1_crypt':
        return ldap_sha1_crypt.hash(args.text)
    elif args.encrypt == 'ldap_sha256_crypt':
        return ldap_sha256_crypt.hash(args.text)
    elif args.encrypt == 'ldap_sha512_crypt':
        return ldap_sha512_crypt.hash(args.text)
    elif args.encrypt == 'apr_md5_crypt':
        return apr_md5_crypt.hash(args.text)
    elif args.encrypt == 'md5_crypt':
        return md5_crypt.hash(args.text)
    elif args.encrypt == 'plaintext':
        return plaintext.hash(args.text)
    elif args.encrypt == 'unix_disabled':
        return unix_disabled.hash(args.text)
    elif args.encrypt == 'unix_fallback':
        return unix_fallback.hash(args.text)
    elif args.encrypt == 'mssql2000':
        return mssql2000.hash(args.text)
    elif args.encrypt == 'mssql2005':
        return mssql2005.hash(args.text)
    elif args.encrypt == 'mysql323':
        return mysql323.hash(args.text)
    elif args.encrypt == 'mysql41':
        return mysql41.hash(args.text)
    elif args.encrypt == 'atlassian_pbkdf2_sha1':
        return atlassian_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'cta_pbkdf2_sha1':
        return cta_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'dlitz_pbkdf2_sha1':
        return dlitz_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'grub_pbkdf2_sha512':
        return grub_pbkdf2_sha512.hash(args.text)
    elif args.encrypt == 'pbkdf2_sha1':
        return pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'pbkdf2_sha512':
        return pbkdf2_sha512.hash(args.text)
    elif args.encrypt == 'phpass':
        return phpass.hash(args.text)
    elif args.encrypt == 'roundup_plaintext':
        return roundup_plaintext.hash(args.text)
    elif args.encrypt == 'sun_md5_crypt':
        return sun_md5_crypt.hash(args.text)
    elif args.encrypt == 'scram':
        return scram.hash(args.text)
    elif args.encrypt == 'scrypt':
        return scrypt.hash(args.text)
    elif args.encrypt == 'sha1_crypt':
        return sha1_crypt.hash(args.text)
    elif args.encrypt == 'sha256_crypt':
        return sha256_crypt.hash(args.text)
    elif args.encrypt == 'sha512_crypt':
        return sha512_crypt.hash(args.text)
    elif args.encrypt == 'bsd_nthash':
        return bsd_nthash.hash(args.text)
    elif args.encrypt == 'lmhash':
        return lmhash.hash(args.text)
    elif args.encrypt == 'nthash':
        return nthash.hash(args.text)
Beispiel #25
0
def Userregistration(request):
    userid = request.session.get('userid')
    if userid:
        return redirect('forums:forum')
    if request.method == "POST":
        context = {}
        print("hello")
        if request.POST.get("Username") and request.POST.get("Useremail") and request.POST.get(
                "Firstname") and request.POST.get("Lastname") and request.POST.get("password"):
            Usercount = Userreg.objects.filter(Username=request.POST.get("Username")).count()
            emailcount = Userreg.objects.filter(Useremail=request.POST.get("Useremail")).count()
            passlength = request.POST.get("password")
            print("hello")
            try:
                print(Usercount)

                if Usercount < 1:
                    if emailcount < 1:
                        if len(passlength) > 6:
                            # hash password
                            encpassword = pbkdf2_sha256.hash(request.POST.get("password"))
                            print(encpassword)
                            saverecord = Userreg()
                            saverecord.Username = request.POST.get("Username")
                            saverecord.password = encpassword
                            saverecord.Firstname = request.POST.get("Firstname")
                            saverecord.Lastname = request.POST.get("Lastname")
                            saverecord.Useremail = request.POST.get("Useremail")

                            saverecord.save()
                            nowregistered = Userreg.objects.filter(Useremail=request.POST.get("Useremail"),
                                                                   Username=request.POST.get("Username"),
                                                                   Firstname=request.POST.get("Firstname"),
                                                                   Lastname=request.POST.get("Lastname"))
                            current_site = get_current_site(request)
                            print(current_site)
                            print(nowregistered[0])
                            email_contents = {
                                'user': nowregistered[0],
                                'domain': current_site.domain,
                                'uid': urlsafe_base64_encode(force_bytes(nowregistered[0].pk)),
                                'token': account_activation_token.make_token(nowregistered[0])

                            }

                            link = reverse('activate',
                                           kwargs={'uidb64': email_contents['uid'], 'token': email_contents['token']})

                            activate_url = 'http://' + current_site.domain + link
                            message_name = 'Activate your account'
                            message_email = request.POST.get("Useremail")
                            message = "Activate your account on Aim Arena by using the link provided below + \n" + activate_url
                            msg = EmailMessage(message_name,
                                               message, to=[message_email])
                            msg.send()
                            return redirect('../../auth/signin/')
                        else:
                            messages.error(request, "Password too short")

                            return render(request, 'signup.html')

                    else:
                        messages.error(request, "This email is already registered on this website")

                        return render(request, 'signup.html')


                else:
                    messages.error(request, "This username already exists")

                    return render(request, 'signup.html')

            except:
                error = "An unexpected error occured"
                print(error)
                context = {"error": error}
                return render(request, 'signup.html', context)


    else:
        return render(request, 'signup.html')
Beispiel #26
0
def hash_password(password):
    return pbkdf2_sha256.hash(password)
Beispiel #27
0
def register():
    form = RegisterForm(request.form)

    if request.method == 'POST' and form.validate():
        if User.query.filter_by(username=request.form['username']).first():          
            username = User.query.filter_by(username=request.form['username']).first().username
            if form.username.data == username:
                flash("Username exists.",'danger')
                return redirect(url_for('register'))    
        if User.query.filter_by(email=request.form['email']).first():          
            email = User.query.filter_by(email=request.form['email']).first().email
            if form.email.data == email:
                flash("Email exists.",'danger')
                return redirect(url_for('register'))
        else:        
            user = User(name = form.name.data, email = form.email.data, username = form.username.data, password = pbkdf2_sha256.hash(str(form.password.data)),balance='200000')
            db.session.add(user)
            db.session.commit()

            flash('Your are now registered. Please login to continue.', 'success')
            return redirect(url_for('login'))

    return render_template('register.html',form=form)
Beispiel #28
0
 def _enc_pwd(self, pwd):
     return pwd_hasher.hash(pwd)
Beispiel #29
0
 def get_password_hash(password):
     return sha256.hash(password)
Beispiel #30
0
def sha256_help():
	if 'value' in request.args:
		return pbkdf2_sha256.hash(request.args['value'])
Beispiel #31
0
 def generate_hash(password):
     """
     I don't know what to write here
     """
     return sha256.hash(password)
Beispiel #32
0
def create_hash(string):
    # https://passlib.readthedocs.io/en/stable/narr/hash-tutorial.html
    return pbkdf2_sha256.hash(string)
Beispiel #33
0
 def hash_password(self, password: str):
     self.password_hash = pbkdf2_sha256.hash(password)
Beispiel #34
0
def install_waptserver_service(options,conf=None):
    if setuphelpers.service_installed('WAPTServer'):
        if setuphelpers.service_is_running('WAPTServer'):
            setuphelpers.service_stop('WAPTServer')
        setuphelpers.service_delete('WAPTServer')

    if conf is None:
        conf = waptserver.config.load_config(options.configfile)

    conf_dir =  os.path.join(wapt_root_dir,'conf')
    if not os.path.isdir(conf_dir):
        os.makedirs(conf_dir)
    run(r'icacls "%s" /t /grant  "*S-1-5-20":(OI)(CI)(M)' % conf_dir)

    print("install waptserver")
    service_binary = os.path.abspath(os.path.join(wapt_root_dir,'waptpython.exe'))
    service_parameters = '"%s"' % os.path.join(wapt_root_dir,'waptserver','server.py')
    service_logfile = os.path.join(log_directory, 'nssm_waptserver.log')
    service_dependencies = 'WAPTPostgresql'
    install_windows_nssm_service('WAPTServer',service_binary,service_parameters,service_logfile,service_dependencies)

    tasks_db = os.path.join(wapt_root_dir,'db')
    mkdir_p(tasks_db)
    setuphelpers.run(r'icacls "%s" /grant  "*S-1-5-20":(OI)(CI)(M)' % tasks_db)

    if not conf.get('secret_key'):
        conf['secret_key'] = ''.join(random.SystemRandom().choice(string.letters + string.digits) for _ in range(64))
        waptserver.config.write_config_file(options.configfile,conf)

    if options.setpassword:
        conf['wapt_password'] = pbkdf2_sha256.hash(base64.b64decode(options.setpassword).encode('utf8'))
        waptserver.config.write_config_file(options.configfile,conf)

    clients_signing_certificate =  conf.get('clients_signing_certificate')
    clients_signing_key = conf.get('clients_signing_key')

    if not clients_signing_certificate or not clients_signing_key:
        clients_signing_certificate = os.path.join(wapt_root_dir,'conf','ca-%s.crt' % fqdn())
        clients_signing_key = os.path.join(wapt_root_dir,'conf','ca-%s.pem' % fqdn())

        conf['clients_signing_certificate'] = clients_signing_certificate
        conf['clients_signing_key'] = clients_signing_key
        waptserver.config.write_config_file(options.configfile,conf)

    if clients_signing_certificate is not None and clients_signing_key is not None and not os.path.isfile(clients_signing_certificate):
        print('Create a certificate and key for clients certificate signing')

        key = SSLPrivateKey(clients_signing_key)
        if not os.path.isfile(clients_signing_key):
            print('Create SSL RSA Key %s' % clients_signing_key)
            key.create()
            key.save_as_pem()

        crt = key.build_sign_certificate(cn=fqdn(),is_code_signing=False,is_ca=True)
        print('Create X509 cert %s' % clients_signing_certificate)
        crt.save_as_pem(clients_signing_certificate)

    # ensure Packages index
    repo = WaptLocalRepo(conf['wapt_folder'])
    repo.update_packages_index()

    if setuphelpers.service_installed('WAPTServer'):
        if not setuphelpers.service_is_running('WAPTServer'):
            setuphelpers.service_start('WAPTServer')
Beispiel #35
0
def create_hash(string):
    # https://passlib.readthedocs.io/en/stable/narr/hash-tutorial.html
    return pbkdf2_sha256.hash(string)
Beispiel #36
0
def main():
    global wapt_folder,NGINX_GID

    parser = OptionParser(usage=usage, version=__version__)
    parser.add_option(
        '-c',
        '--config',
        dest='configfile',
        default=waptserver.config.DEFAULT_CONFIG_FILE,
        help='Config file full path (default: %default)')
    parser.add_option(
        "-s",
        "--force-https",
        dest="force_https",
        default=False,
        action='store_true',
        help="Use https only, http is 301 redirected to https (default: False). Requires a proper DNS name")
    parser.add_option(
        '-q',
        '--quiet',
        dest='quiet',
        default=False,
        action="store_true",
        help='Run quiet postconfiguration - default password and simple behavior')

    (options, args) = parser.parse_args()

    quiet = options.quiet

    if not quiet:
        if postconf.yesno("Do you want to launch post configuration tool ?") != postconf.DIALOG_OK:
            print "canceling wapt postconfiguration"
            sys.exit(1)
    else:
        print('WAPT silent post-configuration')

    # SELinux rules for CentOS/RedHat
    if type_redhat():
        if re.match('^SELinux status:.*enabled', run('sestatus')):
            if not quiet:
                postconf.msgbox('SELinux detected, tweaking httpd permissions.')
                selinux_rules()
                postconf.msgbox('SELinux correctly configured for Nginx reverse proxy')
            else:
                print('[*] Redhat/Centos detected, tweaking SELinux rules')
                selinux_rules()
                print('[*] Nginx - SELinux correctly configured for Nginx reverse proxy')

    # Load existing config file
    server_config = waptserver.config.load_config(options.configfile)

    if os.path.isfile(options.configfile):
        print('[*] Making a backup copy of the configuration file')
        datetime_now = datetime.datetime.now()
        shutil.copyfile(options.configfile,'%s.bck_%s'%  (options.configfile,datetime_now.isoformat()) )

    wapt_folder = server_config['wapt_folder']

    # add secret key initialisation string (for session token)
    if not server_config['secret_key']:
        server_config['secret_key'] = ''.join(random.SystemRandom().choice(string.letters + string.digits) for _ in range(64))

    # add user db and password in ini file
    if server_config['db_host'] in (None,'','localhost','127.0.0.1','::1'):
        ensure_postgresql_db(db_name=server_config['db_name'],db_owner=server_config['db_name'],db_password=server_config['db_password'])

    # Password setup/reset screen
    if not quiet:
        if not server_config['wapt_password'] or \
                postconf.yesno("Do you want to reset admin password ?",yes_label='skip',no_label='reset') != postconf.DIALOG_OK:
            wapt_password_ok = False
            while not wapt_password_ok:
                wapt_password = ''
                wapt_password_check = ''

                while wapt_password == '':
                    (code,wapt_password) = postconf.passwordbox("Please enter the wapt server password (min. 10 characters):  ", insecure=True,width=100)
                    if code != postconf.DIALOG_OK:
                        exit(0)

                while wapt_password_check == '':
                    (code,wapt_password_check) = postconf.passwordbox("Please enter the wapt server password again:  ", insecure=True,width=100)
                    if code != postconf.DIALOG_OK:
                        exit(0)

                if wapt_password != wapt_password_check:
                    postconf.msgbox('Password mismatch !')
                elif len(wapt_password) < 10:
                    postconf.msgbox('Password must be at least 10 characters long !')
                else:
                    wapt_password_ok = True

            password = pbkdf2_sha256.hash(wapt_password.encode('utf8'))
            server_config['wapt_password'] = password
    else:
        wapt_password = ''
        if not server_config['wapt_password']:
            print('[*] Generating random password for WAPT server')
            wapt_password = pwd.genword(entropy=56, charset="ascii_62")
            print('[*] WAPT admin password : %s' % wapt_password)
            password = pbkdf2_sha256.hash(wapt_password.encode('utf8'))
            server_config['wapt_password'] = password

    if not server_config['server_uuid']:
        server_config['server_uuid'] = str(uuid.uuid1())

    # waptagent authentication method
    if not quiet:
        choices = [
                ("1","Allow unauthenticated registration, same behavior as WAPT 1.3", True),
                ("2","Enable kerberos authentication required for machines registration", False),
                ("3","Disable Kerberos but registration require strong authentication", False),
                ]

        code, t = postconf.radiolist("WaptAgent Authentication type?", choices=choices,width=120)
        if code=='cancel':
            print("\n\npostconfiguration canceled\n\n")
            sys.exit(1)
        if t=="1":
            server_config['allow_unauthenticated_registration'] = True
            server_config['use_kerberos'] = False
        if t=="2":
            server_config['allow_unauthenticated_registration'] = False
            server_config['use_kerberos'] = True
        if t=="3":
            server_config['allow_unauthenticated_registration'] = False
            server_config['use_kerberos'] = False
    else:
        print('[*] Set default registration method to : Allow anyone to register + Kerberos disabled')
        server_config['allow_unauthenticated_registration'] = True
        server_config['use_kerberos'] = False


    # Guess fqdn using socket
    fqdn = guess_fqdn()

    clients_signing_certificate =  server_config.get('clients_signing_certificate')
    clients_signing_key = server_config.get('clients_signing_key')

    if not clients_signing_certificate or not clients_signing_key:
        clients_signing_certificate = os.path.join(wapt_root_dir,'conf','ca-%s.crt' % fqdn)
        clients_signing_key = os.path.join(wapt_root_dir,'conf','ca-%s.pem' % fqdn)

        server_config['clients_signing_certificate'] = clients_signing_certificate
        server_config['clients_signing_key'] = clients_signing_key

    if clients_signing_certificate is not None and clients_signing_key is not None and not os.path.isfile(clients_signing_certificate):
        print('Create a certificate and key for clients certificate signing')

        key = SSLPrivateKey(clients_signing_key)
        if not os.path.isfile(clients_signing_key):
            print('Create SSL RSA Key %s' % clients_signing_key)
            key.create()
            key.save_as_pem()

        crt = key.build_sign_certificate(cn=fqdn,is_code_signing=False,is_ca=True)
        print('Create X509 cert %s' % clients_signing_certificate)
        crt.save_as_pem(clients_signing_certificate)

    waptserver.config.write_config_file(cfgfile=options.configfile,server_config=server_config,non_default_values_only=True)

    print('[*] Protecting WAPT config file')
    run("/bin/chmod 640 %s" % options.configfile)
    run("/bin/chown wapt %s" % options.configfile)

    print('[*] Update WAPT repository')
    repo = WaptLocalRepo(wapt_folder)
    repo.update_packages_index(force_all=True)

    final_msg = ['[*] Postconfiguration completed.',]
    if not quiet:
        postconf.msgbox("Press ok to start waptserver and wapttasks daemons")
    enable_waptserver()
    start_waptserver()

    # In this new version Apache is replaced with Nginx? Proceed to disable Apache. After migration one can remove Apache install altogether
    stop_disable_httpd()

    # Nginx configuration
    if quiet:
        try:
            generate_dhparam()
            nginx_cleanup()
            make_httpd_config('/opt/wapt/waptserver', fqdn, options.force_https,server_config)
            enable_nginx()
            restart_nginx()
            setup_firewall()
        except subprocess.CalledProcessError as cpe:
            final_msg += [
                'Error while trying to configure Nginx!',
                'errno = ' + str(cpe.returncode) + ', output: ' + cpe.output
                ]
        except Exception as e:
                import traceback
                final_msg += [
                'Error while trying to configure Nginx!',
                traceback.format_exc()
                ]
    else:
        reply = postconf.yesno("Do you want to configure nginx?")
        if reply == postconf.DIALOG_OK:
            try:
                msg = 'FQDN for the WAPT server (eg. wapt.acme.com)'
                (code, reply) = postconf.inputbox(text=msg, width=len(msg)+4, init=fqdn)
                if code != postconf.DIALOG_OK:
                    exit(1)
                else:
                    fqdn = reply

                generate_dhparam()
                nginx_cleanup()

                if server_config['use_kerberos']:
                    if type_debian():
                        if not check_if_deb_installed('libnginx-mod-http-auth-spnego'):
                            print('[*] Nginx - Missing dependency libnginx-mod-http-auth-spnego, please install first before configuring kerberos')
                            sys.exit(1)

                make_httpd_config('/opt/wapt/waptserver', fqdn, options.force_https, server_config)
                final_msg.append('Please connect to https://' + fqdn + '/ to access the server.')
                postconf.msgbox("The Nginx config is done. We need to restart Nginx?")
                run_verbose('systemctl enable nginx')
                run_verbose('systemctl restart nginx')
                setup_firewall()

            except subprocess.CalledProcessError as cpe:
                final_msg += [
                    'Error while trying to configure Nginx!',
                    'errno = ' + str(cpe.returncode) + ', output: ' + cpe.output
                    ]
            except Exception as e:
                import traceback
                final_msg += [
                'Error while trying to configure Nginx!',
                traceback.format_exc()
                ]

    final_msg.append('Please connect to https://' + fqdn + '/ to access the server.')

    # Check if Mongodb > PostgreSQL migration is necessary
    if not quiet:
        if check_mongo2pgsql_upgrade_needed(options.configfile) and\
                postconf.yesno("It is necessary to migrate current database backend from mongodb to postgres. Press yes to start migration",no_label='cancel') == postconf.DIALOG_OK:
            upgrade2postgres(options.configfile)
    else:
        if check_mongo2pgsql_upgrade_needed(options.configfile):
            upgrade2postgres(options.configfile)

    # Final message
    if not quiet:
        width = 4 + max(10, len(max(final_msg, key=len)))
        height = 2 + max(20, len(final_msg))
        postconf.msgbox('\n'.join(final_msg), height=height, width=width)
    else:
        if wapt_password:
            final_msg.append('[*] WAPT admin password : %s\n' % wapt_password)
        for line in final_msg:
            print(line)
from app import db
from tables import User
from passlib.hash import pbkdf2_sha256

username = input("Username:"******"Password:"******"Truck Owner(y/n):")
if truck_owner == "y":
    truck_id = input("Truck ID:")

if User.query.filter_by(username=username).first() is None:
    password_hash = pbkdf2_sha256.hash(password)
    if truck_owner == "y":
        user = User(username=username,
                    password=password_hash,
                    rank="truck",
                    owner_truck_id=truck_id)
    else:
        user = User(username=username, password=password_hash, rank="admin")
    db.session.add(user)
    db.session.commit()