AIL-framework/var/www/create_default_user.py

67 lines
2.2 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
# -*-coding:UTF-8 -*
import os
import sys
import redis
import configparser
import bcrypt
import secrets
# Import config
sys.path.append('./modules/')
def get_all_role():
return r_serv_db.zrange('ail:all_role', 0 , -1)
def hashing_password(bytes_password):
hashed = bcrypt.hashpw(bytes_password, bcrypt.gensalt())
return hashed
def create_user_db(username_id , password, default=False, role=None, update=False):
password = password.encode()
password_hash = hashing_password(password)
r_serv_db.hset('user:all', username_id, password_hash)
if update:
r_serv_db.hdel('user_metadata:{}'.format(username_id), 'change_passwd')
else:
if default:
r_serv_db.hset('user_metadata:{}'.format(username_id), 'change_passwd', True)
if role:
if role in get_all_role():
r_serv_db.sadd('user_role:{}'.format(role), username_id)
if __name__ == "__main__":
configfile = os.path.join(os.environ['AIL_BIN'], 'packages/config.cfg')
if not os.path.exists(configfile):
raise Exception('Unable to find the configuration file. \
Did you set environment variables? \
Or activate the virtualenv.')
cfg = configparser.ConfigParser()
cfg.read(configfile)
r_serv_db = redis.StrictRedis(
host=cfg.get("ARDB_DB", "host"),
port=cfg.getint("ARDB_DB", "port"),
db=cfg.getint("ARDB_DB", "db"),
decode_responses=True)
username = 'admin@admin.test'
password = secrets.token_urlsafe()
create_user_db(username, password, role='admin', default=True)
# create user token
token = secrets.token_urlsafe(41)
r_serv_db.hset('user:tokens', token, username)
default_passwd_file = os.path.join(os.environ['AIL_HOME'], 'DEFAULT_PASSWORD')
to_write_str = '# Password Generated by default\n# This file is deleted after the first login\n#\nemail=admin@admin.test\npassword='
to_write_str = to_write_str + password + '\nAPI_Key=' + token
with open(default_passwd_file, 'w') as f:
f.write(to_write_str)
print('new user created: {}'.format(username))
print('password: {}'.format(password))