Ejemplo n.º 1
0
def create_user():
    """
    Creates a user in the database
    """
    email = prompt("Please enter your email address ?", default='*****@*****.**')

    password_match = False
    while not password_match:
        password = prompt_pass("Please enter your password ?", default='password')
        confirm_password = prompt_pass("Please confirm your password ?", default='password')
        password_match = password == confirm_password

    role = prompt_choices("Please enter your role ?",
                          choices=[role.name for role in user_datastore.role_model.query],
                          resolve=str,
                          default='user')

    first_name = prompt("Please enter your first name ?", default="user")
    last_name = prompt("Please enter your first name ?", default="name")
    user_name = prompt("Please enter your first name ?", default="uname")

    user_datastore.create_user(email=email,
                               password=encrypt_password(password),
                               roles=[role],
                               first_name=first_name.capitalize(),
                               last_name=last_name.capitalize(),
                               user_name=user_name)
    user_datastore.commit()
Ejemplo n.º 2
0
def createsuperuser():
    """
    Create a super user of the system, requiring Email and password.
    """

    db = mongo.db
    username = prompt('username')

    if len(username) < 2:
        sys.exit('\nUserName must be at least two characters long')

    user = db.user.find_one({username: username})
    if user:
        sys.exit('\nUserName already exists. Please select another one.')

    password = prompt_pass('User password')
    if len(password) < 6 or len(password) > 20:
        sys.exit('\nPassword length must be between 6 and 20.')
    password_confirm = prompt_pass('Confirmed password')

    if not password == password_confirm:
        sys.exit('\nCould not create user: Passwords did not match')

    db.user.insert_one({
        "username": username,
        "is_admin": 1,
        "password": encrypt_password(password)
    })
Ejemplo n.º 3
0
def admin():
    adm = tables.User.query.filter_by(admin=2).first()
    if adm is None:
        while (True):
            name = prompt("Please enter the administrator's name")
            if name == None:
                print("You must enter a name!!!")
            else:
                if prompt_bool("Correct name?", default=True):
                    break
        while (True):
            email = prompt("Enter admin email")
            if email == None:
                print("You must enter an email!!!")
            else:
                if prompt_bool("Email Correct?", default=True):
                    break
        while (True):
            password = prompt_pass("Enter the administrator password")
            password_v = prompt_pass("Re-enter password")
            if password == None or password_v == None or password != password_v:
                print("You must enter a valid password!!!")
            else:
                if prompt_bool("Password correct?", default=True):
                    break
        adm = tables.User(name=name, password=password, email=email, admin=2)
        adm.hash_password(password)
        db.session.add(adm)
        db.session.commit()
        print("Admin created!")
    else:
        print("Admin already exists!")
Ejemplo n.º 4
0
def make_yodlee_user():
    email = prompt('Email')
    password = prompt_pass('Password')
    password_confirm = prompt_pass('Confirm Password')

    if password != password_confirm:
        logging.error('Passwords not equal')
        sys.exit()

    response = yc.get_cobrand_login()
    cobrand_session_token, errors = cobrand_session_token_schema.load(
        response.json())
    if errors:
        sys.exit()

    user = User(email=email)
    user.save()

    response = yc.register_user(
        cobrand_session_token,
        user.username,
        password,
        email,
    )
    yodlee_user, errors = user_schema.load(response)
    if errors:
        logging.error('response: {}'.format(response))

    user.yodlee_user_id = yodlee_user.yodlee_user_id
    user.save()
Ejemplo n.º 5
0
    def register_user(self):
        """Prompt for user details."""
        # Get the information.
        email = prompt('Email')
        name = prompt('Name')
        password = prompt_pass('Password')
        password_confirm = prompt_pass('Confirm Password')

        data = MultiDict({
            'email': email,
            'password': password,
            'password_confirm': password_confirm,
        })

        # Validate the form.
        form = RegisterForm(data, csrf_enabled=False)
        if form.validate():
            # Register the new user.
            user = register_user(name=name, email=email, password=password)

            print('\nUser created successfully.')
            print('User(id={} email={})'.format(user.id, user.email))

            return user

        # If something went wrong, report it and exit out.
        print('\nError creating user:'******'\n'.join(errors))
        sys.exit(1)
Ejemplo n.º 6
0
def create_user():
    username = prompt('用户名').strip()
    password = prompt_pass('密码').strip()
    repassword = prompt_pass('重复密码').strip()
    is_super = prompt_bool('超级用户')
    is_staff = prompt_bool('后台用户')

    if not all([username, password, repassword]):
        print('请输入完整数据')
        return 
    if password != repassword:
        print('两次输入密码不同')
        return

    connect_db()

    user = User()
    user.username = username
    user.password = password
    user.is_super = is_super
    user.is_staff = is_staff

    db_session.add(user)
    db_session.commit()
    print('创建用户成功!')
Ejemplo n.º 7
0
    def run(self):
        username = prompt("请输入用户名")
        with app.app_context():
            g_db = db.session
            while True:
                old_user = models.User.query.filter_by(
                    username=username).first()
                if old_user:
                    print "用户名重复"
                    username = prompt("请重新输入用户名")
                else:
                    break
            nickname = prompt("请输入昵称")
            while True:
                password = prompt_pass("请输入密码")
                confirm_password = prompt_pass("再次输入密码")
                if password != confirm_password:
                    print "创建失败, 两次密码不一致"
                    continue
                break

            super_user = models.User(username,
                                     nickname,
                                     password,
                                     "",
                                     is_superuser=True)
            g_db.add(super_user)
            g_db.commit()
            print super_user.create_date.strftime("%Y%m%d%H%M%S")
            print "创建超级用户:%s成功" % username
Ejemplo n.º 8
0
def createuser(username=None, password=None, admin=None):
    """Create a user account for the application.
    """
    u_name = username
    pw = password
    make_admin = admin

    if u_name is None:
        while True:
            u_name = prompt("User Name")
            user = User.query.filter(User.name == u_name).first()
            if user is not None:
                print("{}: USER ALREADY EXISTS!".format(u_name))
            else:
                break

    if pw is None:
        pw = prompt_pass("Password")
        while True:
            pw_again = prompt_pass("Password Again")
            if pw != pw_again:
                print("PASSWORDS DO NOT MATCH!")
            else:
                break

    if make_admin is None:
        make_admin = prompt_bool("Do you wish to make {} an administrator?".\
                                 format(u_name))

    user = User(name=u_name, password="", admin=make_admin, enabled=True)
    user.set_password(pw)

    db.session.add(user)
    db.session.commit()
    print("Successfully created '{}' with ID: {}.".format(user.name, user.id))
Ejemplo n.º 9
0
def createsuperuser():
    """"
    
    a funtion that createSuperUser in terminal
    
    """
    username = prompt('username')
    email = prompt('Email')
    password = prompt_pass('password')
    confirm_password = prompt_pass('Confirmed password')

    if password != confirm_password:
        sys.exit('\n Sorry your apssword is not correct')

    hashed_passowrd = bcrypt.generate_password_hash(confirm_password).decode(
        'utf-8')
    user = User(username=username,
                email=email,
                password=hashed_passowrd,
                is_admin=True)

    db.session.add(user)
    db.session.commit()


#manager.add_command("createsuperuser",createsuperuser())
#manager.add_command('create_db', create())
Ejemplo n.º 10
0
def createsuperuser():
    """Create a superuser, requires username, email and password."""
    db.tables_creation()

    username = prompt('superuser username')

    email = prompt('superuser email')
    confirm_email = prompt('confirm superuser email')

    if not EMAIL_REGEX.match(email):
        sys.exit('\n kindly provide a valid email address')

    if not email == confirm_email:
        sys.exit('\n kindly ensure that email and confirm email are identical')

    password = prompt_pass('superuser password')
    confirm_password = prompt_pass('confirm superuser password')

    if len(password) < 8:
        sys.exit(
            '\n kindly ensure that the password is at leaast 8 characters long'
        )

    if not password == confirm_password:
        sys.exit(
            '\n kindly ensure that password and confirm password are identical'
        )
    admin = True

    models.User(username=username, email=email, password=password, admin=admin)
    sys.exit('\n superuser successfully created')
Ejemplo n.º 11
0
 def get_password_from_prompt(self):
     """Get password from the command line prompt."""
     first_password = prompt_pass('Enter password')
     second_password = prompt_pass('Enter password again')
     if first_password != second_password:
         sys.stderr.write('Passwords don\'t match, try again.\n')
         self.get_password_from_prompt()
     return first_password
Ejemplo n.º 12
0
 def get_password_from_prompt(self):
     """Get password from the command line prompt."""
     first_password = prompt_pass('Enter password')
     second_password = prompt_pass('Enter password again')
     if first_password != second_password:
         sys.stderr.write('Passwords don\'t match, try again.\n')
         self.get_password_from_prompt()
     return first_password
Ejemplo n.º 13
0
def create_superadmin(email):
    password = prompt_pass('Please input password')
    confirm_password = prompt_pass('Please input password again')
    if password != confirm_password:
        print('Password mismatch! Please confirm that you type same passwords.')
        return
    current_app.extensions['perm'].create_super_admin(email, password)
    print('Success!')
Ejemplo n.º 14
0
 def run(self):
     email = prompt('Email Address')
     password = prompt_pass('Password')
     if password == prompt_pass('Confirm Password'):
         user = app.user_datastore.create_user(email=email, password=encrypt_password(password))
         app.user_datastore.activate_user(user)
         db.session.commit()
         self.stdout.write('New User Created, <{id} : {email}>'.format(id=user.id, email=user.email))
     else:
         self.stderr.write('Passwords did not match!')
Ejemplo n.º 15
0
def create_user():
    username = prompt("Enter username")
    password1 = prompt_pass("Enter password")
    password2 = prompt_pass("Re-type password")
    if password1 == password2:
        new_user = models.User(username, password1)
        models.db.session.add(new_user)
        models.db.session.commit()
        print('User {0} successfully created'.format(username))
    else:
        print("Error: Passwords don't match")
Ejemplo n.º 16
0
def createuser(username=None, password=None, email=None, role=None):
    """
    Create a new user
    """
    
    if username is None:
        while True:
            username = prompt("Username")
            user = User.query.filter(User.username==username).first()
            if user is not None:
                print "Username %s is already taken" % username
            else:
                break

    if email is None:
        while True:
            email = prompt("Email address")
            user = User.query.filter(User.email==email).first()
            if user is not None:
                print "Email %s is already taken" % email
            else:
                break

    if password is None:
        password = prompt_pass("Password")

        while True:
            password_again = prompt_pass("Password again")
            if password != password_again:
                print "Passwords do not match"
            else:
                break
    
    roles = (
        (User.MEMBER, "member"),
        (User.MODERATOR, "moderator"),
        (User.ADMIN, "admin"),
    )

    if role is None:
        role = prompt_choices("Role", roles, resolve=int, default=User.MEMBER)

    user = User(username=username,
                email=email,
                password=password,
                role=role)

    db.session.add(user)
    db.session.commit()

    print "User created with ID", user.id
Ejemplo n.º 17
0
 def run(self):
     email = prompt('Email')
     password = prompt_pass('Password')
     password_confirm = prompt_pass('Confirm Password')
     data = MultiDict(dict(email=email, password=password, password_confirm=password_confirm))
     form = RegisterForm(data, csrf_enabled=False)
     if form.validate():
         user = register_user(email=email, password=password)
         print '\nUser created successfully'
         print 'User(id=%s email=%s)' % (user.id, user.email)
         return
     print '\nError creating user:'******'\n'.join(errors)
Ejemplo n.º 18
0
def create_user(email,
                password,
                role,
                network=None,
                gateway=None,
                confirmed=True,
                quiet=True):
    if email is None:
        email = prompt('Email')

    if password is None:
        password = prompt_pass('Password')
        confirmation = prompt_pass('Confirm Password')

        if password != confirmation:
            print("Passwords don't match")
            return

    if role == 'network-admin':
        if network is None:
            print('Network is required for a network admin')
            return
        if gateway is not None:
            print('Gateway is not required for a network admin')
            return

    if role == 'gateway-admin':
        if network is None:
            print('Network is required for a gateway admin')
            return
        if gateway is None:
            print('Gateway is required for a gateway admin')
            return

    user = users.create_user(email=email, password=encrypt_password(password))

    user.network_id = network
    user.gateway_id = gateway

    if confirmed:
        user.confirmed_at = datetime.datetime.now()

    if role is not None:
        role = Role.query.filter_by(name=role).first()
        user.roles.append(role)

    db.session.commit()

    if not quiet:
        print('User created')
Ejemplo n.º 19
0
def create_admin():
    email = prompt("Enter an email for this Administrator")
    pass1 = prompt_pass("Enter password")
    pass2 = prompt_pass("Re-enter password")

    if pass1 == pass2:
        try:
            admin = models.Admin(email=email)
            admin.password = pass1
            admin.save()
        except:
            print "Email already exists in database."
    else:
        print "Passwords do not match. Try again."
Ejemplo n.º 20
0
 def run(self):
     email = prompt("Email")
     password = prompt_pass("Password")
     password_confirm = prompt_pass("Confirm password")
     data = MultiDict(dict(email=email, password=password,
                           password_confirm=password_confirm))
     form = RegisterForm(data, csrf_enabled=False)
     if form.validate():
         user = register_user(email=email, password=password)
         print "\nUser created."
         print "<User id=%s email=%s>" % (user.id, user.email)
     else:
         print "Error:"
         for errors in form.errors.values():
             print "\n".join(errors)
Ejemplo n.º 21
0
def first_run():
    """
    Init the database and
    query the user for an administrator email/password.
    """
    init_db()

    email = None
    while not email:
        email_tmp = prompt("Administrator email")

        email_test = _DummyEmailField(email_tmp)
        email_validator = Email()
        try:
            email_validator(None, email_test)
        except ValidationError:
            print("Email is invalid")
        else:
            with current_app.app_context():
                if User.query.filter_by(email=email_tmp).first():
                    print("User already exists")
                else:
                    email = email_tmp

    password = None
    while not password:
        password = prompt_pass("Administrator Password")

    add_user(email, password, ("Admin",), True)

    print("Setup complete")
Ejemplo n.º 22
0
def modifypassword(email=None, password=None):
    """비밀번호 변경"""

    User = current_app.user_model

    if not email:
        email = prompt("A valid email address")

    if not password:
        password = prompt_pass("Password")

    if all([email, password]):
        user = User.query.filter_by(email=email).first()

        if not user:
            print('Invalid user <{email}>'.format(email=email))
            sys.exit(0)

        user.set_password(password)
        db.session.add(user)
        db.session.commit()
    else:
        user = "******"

    print(user)
Ejemplo n.º 23
0
Archivo: run.py Proyecto: yehiaa/clinic
def createUser():
    """create new user """
    from app import db
    from app.services.models.user import User
    from app.services.forms.users import CreateUserForm
    name = prompt("name ?")
    userName = prompt("user name ?")
    password = prompt_pass("password ?")

    print([name, userName, password])

    superUser = prompt_bool("Is super user ?")

    user = User(password=password, name=name, userName=userName, allowLogin=True, active=True, isAdmin=superUser)
    form = CreateUserForm(obj=user)

    if form.validate():
        try:
            db.session.add(user)
            db.session.commit()

        except Exception as e:
            print(e)
    else:
        print(form.errors)
Ejemplo n.º 24
0
def create_user(email, password):
    email = email or prompt('Email')
    password = password or prompt_pass('Password')
    user = User(email=email, password=password)
    db.session.add(user)
    db.session.commit()
    print('User created successfully')
Ejemplo n.º 25
0
def create_user():
    """
    Create a new user.
    """
    email = None
    while not email:
        email_tmp = prompt("Email")

        email_test = _DummyEmailField(email_tmp)
        email_validator = Email()
        try:
            email_validator(None, email_test)
        except ValidationError:
            print("Email is invalid")
        else:
            with current_app.app_context():
                if User.query.filter_by(email=email_tmp).first():
                    print("User already exists")
                else:
                    email = email_tmp

    password = None
    while not password:
        password = prompt_pass("Password")

    admin = prompt_bool("Administrator?")

    roles = ("Admin",) if admin else ()

    add_user(email, password, roles)

    print("User added")
Ejemplo n.º 26
0
def createuser(email=None, password=None, role=None):
    """Create a user"""

    if not email:
        email = prompt("A valid email address")

    if not password:
        password = prompt_pass("Password")

    if not role:
        roles = [r.name for r in db.session.query(Role)]
        role_name = prompt_choices("Role",
                                   choices=roles,
                                   no_choice=('none', ''))
        if role_name:
            role = get_or_create(db.session, Role, name=role_name)
        else:
            role = None
    else:
        role = get_or_create(db.session, Role, name=role)

    if all([email, password]):
        user = User.createuser(db.session, email, password, roles=[role])
        db.session.commit()
    else:
        user = "******"

    print(user)
Ejemplo n.º 27
0
def createuser(email=None, password=None, role=None):
    """Create a user"""

    if not email:
        email = prompt("A valid email address")

    if not password:
        password = prompt_pass("Password")

    if not role:
        roles = [r.name for r in db.session.query(Role)]
        role_name = prompt_choices("Role", choices=roles,
                                   no_choice=('none', ''))
        if role_name:
            role = get_or_create(db.session, Role, name=role_name)
        else:
            role = None
    else:
        role = get_or_create(db.session, Role, name=role)

    if all([email, password]):
        user = User.createuser(db.session, email, password, roles=[role])
        db.session.commit()
    else:
        user = "******"

    print(user)
Ejemplo n.º 28
0
def create_user(email, password):
    email = email or prompt('Email')
    password = password or prompt_pass('Password')
    user = User(email=email, password=password)
    db.session.add(user)
    db.session.commit()
    print('User created successfully')
Ejemplo n.º 29
0
def unlock(path=None):
    """
    Decrypts all of the files in a given directory with provided password.
    This is most commonly used during the startup sequence of Lemur
    allowing it to go from source code to something that can communicate
    with external services.

    Path defaults ~/.lemur/keys

    :param: path
    """
    key = prompt_pass("[!] Please enter the encryption password")

    if not path:
        path = os.path.expanduser('~/.lemur/keys')

    dest_dir = os.path.join(path, "decrypted")
    source_dir = os.path.join(path, "encrypted")

    if not os.path.exists(dest_dir):
        sys.stdout.write("[+] Creating decryption directory: {0}\n".format(dest_dir))
        os.makedirs(dest_dir)

    for root, dirs, files in os.walk(source_dir):
        for f in files:
            source = os.path.join(source_dir, f)
            dest = os.path.join(dest_dir, ".".join(f.split(".")[:-1]))
            with open(source, 'rb') as in_file, open(dest, 'wb') as out_file:
                f = Fernet(key)
                data = f.decrypt(in_file.read())
                out_file.write(data)
                sys.stdout.write("[+] Writing file: {0} Source: {1}\n".format(dest, source))

    sys.stdout.write("[+] Keys have been unencrypted!\n")
Ejemplo n.º 30
0
def createuser(email, password, role=None, name=None, first_name=None):
    """Create new user."""
    email = text_type(email)
    if User.query.filter(User.email == email).count() > 0:
        print("A user with email '{}' already exists, aborting.".format(email))
        return

    if password is None:
        password = prompt_pass('Password')

    user = User(
        email=email,
        password=password,
        last_name=name,
        first_name=first_name,
        can_login=True,
    )
    db.session.add(user)

    if role in ('admin',):
        # FIXME: add other valid roles
        security = get_service('security')
        security.grant_role(user, role)

    db.session.commit()
    print("User {} added".format(email))
Ejemplo n.º 31
0
def config(
        mysql=None,
        username=_default,
        password=None,
        server=_server,
        database=_default,
        folder=_folder,
):
    """Generate config.py for AwesomeTitle.

    If there were some given parameters, those questions will be handled
    automatically.
    """
    # TODO : Is Existed config.py?

    base = dirname(abspath(__file__))

    # XXX : Check '-m' or '--mysql' options entered.
    if mysql is None:
        use_mysql = prompt_bool("Use MySQL?", default=True)
    else:
        if mysql == "True":
            use_mysql = True
        elif mysql == "False":
            use_mysql = False
        else:
            raise Exception("`-m` or `--mysql` needed `True` or `False`.")
    if use_mysql is True:
        # XXX : Check '-u' or '--username' options entered.
        if username is _default:
            username = prompt("MySQL DB Username", default=username)
        # XXX : Check '-p' or '--password' options entered.
        if not password:
            password = prompt_pass("MySQL DB Password")
        # XXX : Check '-s' or '--server' options entered.
        if server is _server:
            server = prompt("MySQL DB Server", default=server)
        # XXX : Check '-d' or '--database' options entered.
        if database is _default:
            database = prompt("MySQL DB Database", default=database)
    # XXX : Check '-f' or '--folder' options entered.
    if folder is _folder:
        folder = prompt("Image Upload Folder", default=folder)
    folder = join(base, folder)
    if not exists(folder):
        makedirs(folder)
    secret_key = urandom(24)
    with open("confs/config.py.tmpl") as tmpl:
        Template(
            tmpl.read()
        ).stream(
            base=base,
            username=username,
            password=password,
            server=server,
            database=database,
            folder=folder,
            secret_key=secret_key,
            use_mysql=use_mysql,
        ).dump("AwesomeTitleServer/config.py")
Ejemplo n.º 32
0
def unlock(path=None):
    """
    Decrypts all of the files in a given directory with provided password.
    This is most commonly used during the startup sequence of Lemur
    allowing it to go from source code to something that can communicate
    with external services.

    Path defaults ~/.lemur/keys

    :param: path
    """
    key = prompt_pass("[!] Please enter the encryption password")

    if not path:
        path = os.path.expanduser('~/.lemur/keys')

    dest_dir = os.path.join(path, "decrypted")
    source_dir = os.path.join(path, "encrypted")

    if not os.path.exists(dest_dir):
        sys.stdout.write("[+] Creating decryption directory: {0}\n".format(dest_dir))
        os.makedirs(dest_dir)

    for root, dirs, files in os.walk(source_dir):
        for f in files:
            source = os.path.join(source_dir, f)
            dest = os.path.join(dest_dir, ".".join(f.split(".")[:-1]))
            with open(source, 'rb') as in_file, open(dest, 'wb') as out_file:
                f = Fernet(key)
                data = f.decrypt(in_file.read())
                out_file.write(data)
                sys.stdout.write("[+] Writing file: {0} Source: {1}\n".format(dest, source))

    sys.stdout.write("[+] Keys have been unencrypted!\n")
Ejemplo n.º 33
0
def make_admin_user():
    password = prompt_pass("Password")
    user = User.create(username="******", email="*****@*****.**", password=password, active=True)
    admin_role = Role(name='admin')
    admin_role.save()
    user.roles.append(admin_role)
    user.save()
Ejemplo n.º 34
0
def create(email, name, groups, is_admin=False, google_auth=False, password=None):
    print "Creating user (%s, %s)..." % (email, name)
    print "Admin: %r" % is_admin
    print "Login with Google Auth: %r\n" % google_auth

    org = models.Organization.get_by_slug('default')
    if isinstance(groups, basestring):
        groups= groups.split(',')
        groups.remove('') # in case it was empty string
        groups = [int(g) for g in groups]

    if groups is None:
        groups = [models.Group.get(models.Group.name=="default", models.Group.org==org).id]

    if is_admin:
        groups += [models.Group.get(models.Group.name=="admin", models.Group.org==org).id]

    user = models.User(org=org, email=email, name=name, groups=groups)
    if not google_auth:
        password = password or prompt_pass("Password")
        user.hash_password(password)

    try:
        user.save()
    except Exception, e:
        print "Failed creating user: %s" % e.message
Ejemplo n.º 35
0
 def run(self):
     email = prompt('Email')
     password = prompt_pass('Password')
     password_confirm = prompt_pass('Confirm Password')
     data = MultiDict(
         dict(email=email,
              password=password,
              password_confirm=password_confirm))
     form = RegisterForm(data, csrf_enabled=False)
     if form.validate():
         user = register_user(email=email, password=password)
         print '\nUser created successfully'
         print 'User(id=%s email=%s)' % (user.id, user.email)
         return
     print '\nError creating user:'******'\n'.join(errors)
Ejemplo n.º 36
0
def create_admin(username=None, password=None, email=None):
    """Creates the admin user."""

    if not (username and password and email):
        username = prompt("Username")
        password = prompt_pass("Password")

    create_admin_user(username=username, password=password)
Ejemplo n.º 37
0
 def run(self):
     email = prompt("Email")
     password = prompt_pass("Password")
     password_confirm = prompt_pass("Confirm password")
     data = MultiDict(
         dict(email=email,
              password=password,
              password_confirm=password_confirm))
     form = RegisterForm(data, csrf_enabled=False)
     if form.validate():
         user = register_user(email=email, password=password)
         print "\nUser created."
         print "<User id=%s email=%s>" % (user.id, user.email)
     else:
         print "Error:"
         for errors in form.errors.values():
             print "\n".join(errors)
Ejemplo n.º 38
0
def create_user(admin=False):
    """Creates an user in database"""
    username = prompt("Enter username")
    email = prompt("Enter email")
    password1 = prompt_pass("Enter password")
    password2 = prompt_pass("Re-type password")
    if password1 == password2:
        new_user = User(
            username=username,
            password=password1,
            email=email
        )
        new_user.is_admin = admin
        db.session.add(new_user)
        db.session.commit()
        print('User {0} successfully created'.format(username))
    else:
        print("Error: Passwords don't match")
Ejemplo n.º 39
0
    def run(self, username):
        user = user_service.get_by_username(username)

        if not user:
            sys.stderr.write("[!] No user found for username: {0}\n".format(username))
            sys.exit(1)

        sys.stderr.write("[+] Resetting password for {0}\n".format(username))
        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match\n")
            sys.exit(1)

        user.password = password1
        user.hash_password()
        database.commit()
Ejemplo n.º 40
0
def passwd(email, password=None):
    """Change the password for the given user."""
    user = User.query.filter(User.email == email).one()
    if password is None:
        password = prompt_pass('New password: ')

    user.set_password(password)
    db.session.commit()
    print("Password updated for user {}".format(email))
Ejemplo n.º 41
0
def create_admin(username=None, password=None, email=None):
    """Creates the admin user."""

    if not (username and password and email):
        username = prompt("Username")
        email = prompt("A valid email address")
        password = prompt_pass("Password")

    create_admin_user(username=username, password=password, email=email)
Ejemplo n.º 42
0
    def run(self, username):
        user = user_service.get_by_username(username)

        if not user:
            sys.stderr.write("[!] No user found for username: {0}\n".format(username))
            sys.exit(1)

        sys.stderr.write("[+] Resetting password for {0}\n".format(username))
        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match\n")
            sys.exit(1)

        user.password = password1
        user.hash_password()
        database.commit()
Ejemplo n.º 43
0
def create(first_name=None, last_name=None, email=None, password=None):
    first_name = first_name or prompt('First Name'),
    last_name = last_name or prompt('Last Name'),
    email = email or prompt('Email'),
    password = password or prompt_pass('Password')
    form = RegisterForm(MultiDict(dict(first_name=first_name,
                                       last_name=last_name,
                                       email=email,
                                       password=password,
                                       password_confirm=prompt_pass('Confirm Password'),
                                       accept_tos=True)), csrf_enabled=False)
    if form.validate():
        user = register_user(first_name=first_name, last_name=last_name, email=email, password=password)
        print('%s created successfully' % repr(user))
        return
    print('Error creating user:'******'\n'.join(errors))
Ejemplo n.º 44
0
    def run(self):
        """ flask-security requires email and password fields 
        """
        
        db_conf = current_app.config.get('SQLALCHEMY_DATABASE_URI')
        if not db_conf:
            print('DB URI not found')
            return None

        db_uri = db_conf.split('/')[-1]
        print('>connected to db: {}'.format(db_uri))

        username = prompt('>username')
        user_exists = User.query.filter_by(username=username).first()
        
        if user_exists is not None:
            raise ValidationError('>>a user with that username already exists')
            return None

        _email = prompt('>email')

        try:
            valid_email(_email)
        except ValidationError as e:
            print(e)
            return None

        password = prompt_pass('>password')
        password2 = prompt_pass('>password again')

        if password != password2:
            raise ValidationError('>>the passwords are not the same')
        else:            
            try:
                strong_password(password)
                password = encrypt_password(password)
                user_datastore.create_user(username=username, 
                        password=password, 
                        email=_email)
                db.session.commit()
                print('>added user: {}'.format(username))

            except ValidationError as e:
                print('>>{}'.format(e))
Ejemplo n.º 45
0
def create_user(email, role):
    from flask_security import SQLAlchemyUserDatastore
    from security_monkey.datastore import User
    from security_monkey.datastore import Role
    from flask_security.utils import encrypt_password

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    ROLES = ['View', 'Comment', 'Justify', 'Admin']
    if role not in ROLES:
        sys.stderr.write('[!] Role must be one of [{0}].\n'.format(
            ' '.join(ROLES)))
        sys.exit(1)

    users = User.query.filter(User.email == email)

    if users.count() == 0:
        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match\n")
            sys.exit(1)

        user = user_datastore.create_user(email=email,
                                          password=encrypt_password(password1),
                                          confirmed_at=datetime.now())
    else:
        sys.stdout.write("[+] Updating existing user\n")
        user = users.first()

        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match\n")
            sys.exit(1)

        user.password = encrypt_password(password1)

    user.role = role

    db.session.add(user)
    db.session.commit()
Ejemplo n.º 46
0
def admin_create():

    username = prompt('admin_username')
    email_address = prompt('admin_email')
    password = prompt_pass('admin_password')
    confirm_password = prompt_pass('confrim_admin_password')

    if not password == confirm_password:
        sys.exit('\n sorry password is not correct!!!!!!')

    hash_password = bcrypt.generate_password_hash(confirm_password).decode(
        'utf-8')
    admin = User(username=username,
                 email_address=email_address,
                 password=hash_password,
                 isaadminUser=True)

    db.session.add(admin)
    db.session.commit()
Ejemplo n.º 47
0
def createsuperuser():
    """
    Method for create super user
    """
    username = prompt('Username')
    if not username:
        sys.exit('\nCould not create user: Username is obligatory')

    firstname = prompt('First name')
    if not firstname:
        sys.exit('\nCould not create user: First name is obligatory')

    lastname = prompt('Last name')
    if not lastname:
        sys.exit('\nCould not create user: Last name is obligatory')

    email = prompt('User E-Mail')
    if not email:
        sys.exit('\nCould not create user: E-Mail did not match')

    EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
    if not EMAIL_REGEX.match(email):
        sys.exit('\nCould not create user: Invalid E-Mail addresss')

    password = prompt_pass('User password')
    password_confirm = prompt_pass('Confirmed password')
    if not password == password_confirm:
        sys.exit('\nCould not create user: Passwords did not match')

    user = models.User(
        username=username,
        email=email,
        first_name=firstname,
        last_name=lastname,
        password=password,
        is_active=True,
        is_admin=True
    )

    db.session.add(user)
    db.session.commit()

    print("SuperUser created!")
Ejemplo n.º 48
0
def create_user(email, role):
    from flask_security import SQLAlchemyUserDatastore
    from security_monkey.datastore import User
    from security_monkey.datastore import Role
    from flask_security.utils import encrypt_password

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    ROLES = ['View', 'Comment', 'Justify', 'Admin']
    if role not in ROLES:
        sys.stderr.write('[!] Role must be one of [{0}].\n'.format(' '.join(ROLES)))
        sys.exit(1)

    users = User.query.filter(User.email == email)

    if users.count() == 0:
        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match\n")
            sys.exit(1)

        user = user_datastore.create_user(email=email,
                                          password=encrypt_password(password1),
                                          confirmed_at=datetime.now())
    else:
        sys.stdout.write("[+] Updating existing user\n")
        user = users.first()

        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match\n")
            sys.exit(1)

        user.password = encrypt_password(password1)

    user.role = role

    db.session.add(user)
    db.session.commit()
Ejemplo n.º 49
0
    def run(self, username, email, active, roles):
        role_objs = []
        for r in roles:
            role_obj = role_service.get_by_name(r)
            if role_obj:
                role_objs.append(role_obj)
            else:
                sys.stderr.write("[!] Cannot find role {0}\n".format(r))
                sys.exit(1)

        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match!\n")
            sys.exit(1)

        user_service.create(username, password1, email, active, None, role_objs)
        sys.stdout.write("[+] Created new user: {0}\n".format(username))
Ejemplo n.º 50
0
def make_admin_user():
    password = prompt_pass("Password")
    user = User.create(username="******",
                       email="*****@*****.**",
                       password=password,
                       active=True)
    admin_role = Role(name='admin')
    admin_role.save()
    user.roles.append(admin_role)
    user.save()
Ejemplo n.º 51
0
    def run(self, username, email, active, roles):
        role_objs = []
        for r in roles:
            role_obj = role_service.get_by_name(r)
            if role_obj:
                role_objs.append(role_obj)
            else:
                sys.stderr.write("[!] Cannot find role {0}\n".format(r))
                sys.exit(1)

        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match!\n")
            sys.exit(1)

        user_service.create(username, password1, email, active, None, role_objs)
        sys.stdout.write("[+] Created new user: {0}\n".format(username))
Ejemplo n.º 52
0
def create_admin(username=None, password=None, email=None):
    """Creates the admin user."""

    if not (username and password and email):
        username = prompt("Username")
        email = prompt("A valid email address")
        password = prompt_pass("Password")

    u = User.create_admin_user(username=username, password=password, email=email)
    print ("Creating admin user :%s Sucessful!" % u.username)
Ejemplo n.º 53
0
def passwd(email, password=None):
  """
  Changes the password for the given user.
  """
  user = User.query.filter(User.email == email).one()
  if password is None:
    password = prompt_pass(u'New password: ')

  user.set_password(password)
  db.session.commit()
  print("Password updated for user {}".format(email))
Ejemplo n.º 54
0
def useradd(email):
    """Creates new user."""
    if User.get_by_email(email):
        abort('[%s] exists' % email)
    try:
        password = prompt_pass('Password [%s]' % email)
    except KeyboardInterrupt:
        abort('nothing changed.')
    user = User.create(email, password, is_active=True)
    db.session.commit()
    print('[%s:%s] is created.' % (user.id, user.email))
Ejemplo n.º 55
0
def useradd(email):
    """Creates new user."""
    if User.get_by_email(email):
        abort('[%s] exists' % email)
    try:
        password = prompt_pass('Password [%s]' % email)
    except KeyboardInterrupt:
        abort('nothing changed.')
    user = User.create(email, password, is_active=True)
    db.session.commit()
    print('[%s:%s] is created.' % (user.id, user.email))
Ejemplo n.º 56
0
def superuser(username, email):
    user = User(username, email)
    user.active = True
    user.password = prompt_pass('password')
    db.session.add(user)
    sigil_ctx = AppContext.by_name(app.config['ROOT_APP_CTX'])
    if sigil_ctx:
        for need in sigil_ctx.needs:
            user.permissions.append(need)
    db.session.commit()
    print('user {} added with id {}'.format(user.username, user.id))