예제 #1
0
    def run(self):
        deployments = models.Deployment.objects.all()
        option = prompt_choices('Deployment', [
            (str(i), v) for i, v in enumerate(deployments, 1)])
        deployment = deployments[int(option) - 1]
        name = prompt('Event name')
        start = end = None
        while True:
            try:
                start = datetime.strptime(
                    prompt('Start date (YYYY-MM-DD)'), '%Y-%m-%d')
            except ValueError:
                pass
            if start:
                break
        while True:
            try:
                end = datetime.strptime(
                    prompt('End date (YYYY-MM-DD)'), '%Y-%m-%d')
            except ValueError:
                pass
            if end:
                break

        event, _ = models.Event.objects.get_or_create(
            name=name,
            deployment=deployment)
        event.start_date = datetime.combine(start, datetime.min.time())
        event.end_date = datetime.combine(end, datetime.max.time())
        event.save()
예제 #2
0
파일: commands.py 프로젝트: adityaU/quokka
    def run(self, name=None, email=None, password=None, role=None):
        if not name:
            name = prompt("Full Name")

        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 Role.objects]
            role_name = prompt_choices("Role", choices=roles,
                                       no_choice=('none', ''))
            if role_name:
                role, created = Role.objects.get_or_create(name=role_name)
            else:
                role = None
        else:
            role, created = Role.objects.get_or_create(name=role)

        if all([name, email, password]):
            user = User.objects.create(
                name=name,
                email=email,
                password=encrypt_password(password),
                active=True,
                roles=[role]
            )
        else:
            user = u"Cant create the supersuser"

        print user
예제 #3
0
    def run(self):
        settings = current_app.config

        # construct base url
        hostname = prompt("URL of current instance")
        base_url = urljoin(hostname, url_for("messaging.kannel_view"))

        filename = prompt("Path to message log")
        with open(filename) as f:
            reader = unicodecsv.DictReader(f)
            for row in reader:
                # ignore outbound messages
                if row["Direction"] == "OUT":
                    continue

                msg_time = datetime.strptime(row["Created"], "%Y-%m-%d %H:%M:%S")

                data = {
                    "sender": row["Mobile"].strip(),
                    "text": row["Text"].strip(),
                    "secret": settings.get("MESSAGING_SECRET"),
                    "timestamp": calendar.timegm(msg_time.utctimetuple()),
                }

                requests.get(base_url, params=data)
예제 #4
0
    def run(self):
        """Run the command."""
        # 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():
            user = register_user(name=name, email=email, password=password)
            print('\nUser created successfully.')
            print('User(id={} email={})'.format(user.id, user.email))
            return

        # If something went wrong, report it and exit out.
        print('\nError creating user:'******'\n'.join(errors))
        sys.exit(1)
예제 #5
0
 def run(self):
     email = prompt('Email')
     password = prompt_pass('Password')
     password_confirm = prompt_pass('Confirm Password')
     fullname = prompt('Fullname')
     tel = prompt('Tel')
     active = bool(prompt('Actvice immediately', default='True'))
     role = prompt('Role', default='admin')
     data = MultiDict(
         dict(email=email,
              password=password,
              password_confirm=password_confirm,
              fullname=fullname,
              tel=tel,
              active=active,
              role=role))
     form = RegisterForm(data, csrf_enabled=False)
     if form.validate():
         user = register_user(email=email,
                              password=password,
                              fullname=fullname,
                              tel=tel,
                              active=active,
                              role=role)
         print("\nUser created successfully")
         print("User(id=%s,email=%s,fullname=%s)" %
               (user.id, user.email, user.fullname))
         return
     print("\nError creating user:"******"\n".join(errors))
예제 #6
0
    def run(self):
        email = prompt('Email')
        password = prompt_pass('Password')
        password_confirm = prompt_pass('Confirm Password')

        ListRolesCommand().run()
        role_names = prompt("This user's comma-separated roles")
        role_models = []
        for name in role_names.split(','):
            r = roles.first(name=name.strip())
            if not r:
                print('Invalid role: %s' % name.strip())
            else:
                role_models.append(r)

        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)
            user.roles = role_models
            db.session.add(user)
            db.session.commit()
            print('\nUser created successfully')
            print('User(id=%s email=%s, roles=%s)' % (user.id, user.email,
                ','.join([r.name for r in user.roles])))
        else:
            print('\nError creating user:'******'\n'.join(errors))
예제 #7
0
파일: cards.py 프로젝트: FindBoat/MiliShare
 def run(self):
     channel = prompt('channel')
     content = prompt('content')
     new_card = cards.create(
         channel=channel, content=content, create_time=datetime.now())
     print 'Card(id=%s, channel=%s, content=%s)' % (
         new_card.id, new_card.channel, new_card.content)
예제 #8
0
    def run(self, addroles=True, revision='head', default=False):
        # migrate database to latest revision
        logger.info('Upgrading DB')
        upgrade(revision=revision)

        if addroles:
            logger.info('Inserting Roles into DB')
            Role.insert_roles()

        admin_role = Role.query.filter_by(name='Administrator').one()

        if default:
            admin_email = current_app.config.get('ADMIN_EMAIL', '*****@*****.**')
        else:
            admin_email = prompt('Admin email', default='*****@*****.**')

        existing = User.query.filter(User.email==admin_email).scalar()
        while existing:
            print('Email already registered. Please provide a different email address')
            admin_email = prompt('Admin email', default='*****@*****.**')
            existing = User.query.filter(User.email==admin_email).scalar()

        admin = User(email=admin_email)

        if default:
            admin.password = '******'
        else:
            admin.password = prompt_pass('Admin password')

        db.session.add(admin)
        db.session.commit()
예제 #9
0
 def run(self):
     title = prompt('Title')
     short_title = prompt('Short title')
     url = prompt('URL')
     journal = journals.create( title = title, short_title = short_title, url = url, last_checked = datetime.datetime.utcnow(), next_check = datetime.datetime.utcnow(), metadata_update = datetime.datetime.utcnow() )
     print '\nJournal created successfully'
     print 'Journal(id=%s title=%s)' % (journal.id, journal.title)
예제 #10
0
 def run(self):
     print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
     print 'WARNING!!!!! YOU ARE ABOUT TO DELETE ALL ISSUES!!!!!'
     print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
     c = prompt_bool('Are you sure you wish to continue?')
     if c:
         email = prompt('Enter your administrator email address: ')
         u = User.query.filter_by(email=email).first()
         if u and u.has_role('super'):
             password = prompt('Enter password: '******'Deleting `issue_creators` table'
                 db.engine.execute(issues_creators.delete())
                 print 'Deleting `issues_bundles` table'
                 db.engine.execute(issues_bundles.delete())
                 print 'Deleting `Issue Covers` table'
                 IssueCover.query.delete()
                 print 'Deleting all objects from `Issues` table'
                 Issue.query.delete()
                 db.session.commit()
                 print 'All Issues have been deleted.'
                 print 'You should delete the cover images from the store!'
             else:
                 print 'Incorrect password, Aborting...'
         else:
             print 'User not found or is not an administrator, Aborting...'
     else:
         print 'Aborting...'
         return
예제 #11
0
def create_admin(username=None, password=None, email=None):
    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)
예제 #12
0
    def run(self):
        deployments = models.Deployment.objects.all()
        option = prompt_choices('Deployment',
                                [(str(i), v)
                                 for i, v in enumerate(deployments, 1)])
        deployment = deployments[int(option) - 1]
        name = prompt('Event name')
        start = end = None
        while True:
            try:
                start = datetime.strptime(prompt('Start date (YYYY-MM-DD)'),
                                          '%Y-%m-%d')
            except ValueError:
                pass
            if start:
                break
        while True:
            try:
                end = datetime.strptime(prompt('End date (YYYY-MM-DD)'),
                                        '%Y-%m-%d')
            except ValueError:
                pass
            if end:
                break

        event, _ = models.Event.objects.get_or_create(name=name,
                                                      deployment=deployment)
        event.start_date = datetime.combine(start, datetime.min.time())
        event.end_date = datetime.combine(end, datetime.max.time())
        event.save()
예제 #13
0
    def run(self):
        email = prompt('Email')
        password = prompt_pass('Password')
        password_confirm = prompt_pass('Confirm Password')
        first_name = prompt('First name')
        last_name = prompt('Last name')

        data = MultiDict(
            dict(email=email,
                 password=password,
                 password_confirm=password_confirm,
                 first_name=first_name,
                 last_name=last_name))
        form = RegisterForm(data, csrf_enabled=False)

        if form.validate():
            user = _datastore.create_user(
                email=email,
                password=encrypt_password(password),
                first_name=first_name,
                last_name=last_name,
                active=True,
                confirmed_at=datetime.datetime.utcnow())
            get_or_create_role = _datastore.find_or_create_role("ADMIN")
            _datastore.add_role_to_user(user, get_or_create_role)
            _datastore.commit()

            print('\nUser created successfully')
            print('User(id=%s email=%s)' % (user.id, user.email))
            return

        print('\nError creating user:'******'\n'.join(errors))
예제 #14
0
    def _create_event(deployment):
        name = prompt('Event name')
        start = end = None
        while True:
            try:
                start = datetime.strptime(prompt('Start date (YYYY-MM-DD)'),
                                          '%Y-%m-%d')
            except ValueError:
                pass
            if start:
                break
        while True:
            try:
                end = datetime.strptime(prompt('End date (YYYY-MM-DD)'),
                                        '%Y-%m-%d')
            except ValueError:
                pass
            if end:
                break

        # first, set to start and end of the days entered
        start = datetime.combine(start, datetime.min.time())
        end = datetime.combine(end, datetime.max.time())

        # convert to UTC
        app_timezone = pytz.timezone(settings.TIMEZONE)
        start_utc = app_timezone.localize(start).astimezone(pytz.UTC)
        end_utc = app_timezone.localize(end).astimezone(pytz.UTC)

        event, _ = models.Event.objects.get_or_create(name=name,
                                                      deployment=deployment)
        event.start_date = start_utc
        event.end_date = end_utc
        event.save()
예제 #15
0
def edit_config():
    # Establish the root path on the operating system
    basedir = os.path.abspath(os.path.dirname(__file__))
    # Change the working directory to the backup directory
    os.chdir(basedir + "/app")
    source_file = 'default_config.py'
    edited_file = source_file + '.temp'
    try:
        with open(source_file) as f:
            e = open(edited_file, 'w', 1)
            for lines in f:
                if lines.startswith('CATALOG'):
                    admin = prompt('What is the admins email? (Must match google sign-in!!')
                    e.write("CATALOG_ADMIN = '%s' \n" % (admin, ))
                elif lines.startswith('AWSACCESSKEYID'):
                    aws_key = prompt('Please enter amazon access key: ')
                    e.write("AWSACCESSKEYID = '%s' \n" % (aws_key, ))
                elif lines.startswith('AWSSECRETKEY'):
                    aws_secret = prompt('Please enter amazon secret key: ')
                    e.write("AWSSECRETKEY = '%s' \n" % (aws_secret, ))
                    print 'Successfully added keys and secrets'
                else:
                    e.write(lines)
            # Close both files
            f.close()
            e.close()
            # Delete the original
            os.remove(source_file)
            # Rename the temp with the original file
            os.rename(edited_file, source_file)
    except IOError:
        print 'Sorry. Could not open the file. Please go to default_config and enter the data manually'
예제 #16
0
def client_secrets():

    # Establish the root path on the operating system
    basedir = os.path.abspath(os.path.dirname(__file__))
    # Change the working directory to the backup directory
    os.chdir(basedir + "/app")
    source_file = 'client_secrets.json'
    edit_file = source_file + '.temp'
    with open(source_file) as f:
        e = open(edit_file, 'w', 1)
        for line in f:
            if line.startswith('{'):
                new_line = line.split('need_key')
                client_id = prompt("Enter the client id for Google oauth")
                # Request the key
                secret = prompt('What is the Google client secret?')
                e.write(
                    '%s%s%s%s%s' %
                    (new_line[0], client_id, new_line[1], secret, new_line[2]))
        # Close both files
        f.close()
        e.close()
        # Delete the original
        os.remove(source_file)
        # Rename the temp file with the original name
        os.rename(edit_file, source_file)
    print 'Thank you'
    return
예제 #17
0
 def run(self):
     name = prompt('Role Name')
     description = prompt('Role Description')
     _security_datastore = LocalProxy(lambda: current_app.extensions['security'].datastore)
     _security_datastore.create_role(name=name, description=description)
     db.session.commit()
     return
예제 #18
0
def client_secrets():

    # Establish the root path on the operating system
    basedir = os.path.abspath(os.path.dirname(__file__))
    # Change the working directory to the backup directory
    os.chdir(basedir + "/app")
    source_file = 'client_secrets.json'
    edit_file = source_file + '.temp'
    with open(source_file) as f:
        e = open(edit_file, 'w', 1)
        for line in f:
            if line.startswith('{'):
                new_line = line.split('need_key')
                client_id = prompt("Enter the client id for Google oauth")
                # Request the key
                secret = prompt('What is the Google client secret?')
                e.write('%s%s%s%s%s' % (new_line[0], client_id, new_line[1], secret, new_line[2]))
        # Close both files
        f.close()
        e.close()
        # Delete the original
        os.remove(source_file)
        # Rename the temp file with the original name
        os.rename(edit_file, source_file)
    print 'Thank you'
    return
예제 #19
0
    def run(self):
        settings = current_app.config

        # construct base url
        hostname = prompt('URL of current instance')
        base_url = urljoin(hostname, url_for('messaging.kannel_view'))

        filename = prompt('Path to message log')
        with codecs.open(filename, encoding='utf-8-sig') as f:
            reader = unicodecsv.DictReader(f)
            for row in reader:
                # ignore outbound messages
                if row['Direction'] == 'OUT':
                    continue

                msg_time = pytz.utc.localize(
                    datetime.strptime(row['Created'], '%Y-%m-%d %H:%M:%S'))

                data = {
                    'sender': row['Mobile'].strip(),
                    'text': row['Text'].strip(),
                    'secret': settings.get('MESSAGING_SECRET'),
                    'timestamp': calendar.timegm(msg_time.utctimetuple())
                }

                requests.get(base_url, params=data)
예제 #20
0
    def run(self, name=None, email=None, password=None, role=None):
        if not name:
            name = prompt("Full Name")

        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 Role.objects]
            role_name = prompt_choices("Role",
                                       choices=roles,
                                       no_choice=('none', ''))
            if role_name:
                role, created = Role.objects.get_or_create(name=role_name)
            else:
                role = None
        else:
            role, created = Role.objects.get_or_create(name=role)

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

        print(user)
예제 #21
0
    def run(self):
        settings = current_app.config

        # construct base url
        hostname = prompt('URL of current instance')
        base_url = urljoin(hostname, url_for('messaging.kannel_view'))

        filename = prompt('Path to message log')
        with open(filename) as f:
            reader = unicodecsv.DictReader(f)
            for row in reader:
                # ignore outbound messages
                if row['Direction'] == 'OUT':
                    continue

                msg_time = pytz.utc.localize(datetime.strptime(
                    row['Created'],
                    '%Y-%m-%d %H:%M:%S'))

                data = {
                    'sender': row['Mobile'].strip(),
                    'text': row['Text'].strip(),
                    'secret': settings.get('MESSAGING_SECRET'),
                    'timestamp': calendar.timegm(msg_time.utctimetuple())
                }

                requests.get(base_url, params=data)
예제 #22
0
def createAdmin():
    "Create an Admin User"
    print "Creating Admin User..."
    fname = prompt(name="First Name")
    lname = prompt(name="Last Name")
    email = prompt(name="Email")
    password = prompt_pass(name="password")

    name = {"last": lname,
            "first": fname}

    client = MongoClient()
    db = client.mydb
    users = db.users

    uid = str(uuid.uuid4())
    salt = str(uuid.uuid4())
    m = md5.md5()
    m.update(unicode(salt)+password)
    hashed = m.hexdigest()

    admin = {
        "_id": uid,
        "hash": hashed,
        "name": name,
        "admin": False,
        "salt": salt,
        "email": email,
        "admin": True,
        "tags": [],
        "picture": "http://lorempixel.com/g/250/250/"
    }

    users.insert_one(admin)
예제 #23
0
def createsuperuser():
    """
    Create a super user of the system, requiring Email and password.
    """

    email = prompt('User E-Mail')
    email_confirm = prompt('Confirm E-Mail')

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

    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')

    datastore = SQLAlchemyUserDatastore(db, User, Role)
    datastore.create_user(
        email=email,
        password=encrypt_password(password),
        active=True,
        super_user=True)

    db.session.commit()
예제 #24
0
def edit_config():
    # Establish the root path on the operating system
    basedir = os.path.abspath(os.path.dirname(__file__))
    # Change the working directory to the backup directory
    os.chdir(basedir + "/app")
    source_file = 'default_config.py'
    edited_file = source_file + '.temp'
    try:
        with open(source_file) as f:
            e = open(edited_file, 'w', 1)
            for lines in f:
                if lines.startswith('CATALOG'):
                    admin = prompt(
                        'What is the admins email? (Must match google sign-in!!'
                    )
                    e.write("CATALOG_ADMIN = '%s' \n" % (admin, ))
                elif lines.startswith('AWSACCESSKEYID'):
                    aws_key = prompt('Please enter amazon access key: ')
                    e.write("AWSACCESSKEYID = '%s' \n" % (aws_key, ))
                elif lines.startswith('AWSSECRETKEY'):
                    aws_secret = prompt('Please enter amazon secret key: ')
                    e.write("AWSSECRETKEY = '%s' \n" % (aws_secret, ))
                    print 'Successfully added keys and secrets'
                else:
                    e.write(lines)
            # Close both files
            f.close()
            e.close()
            # Delete the original
            os.remove(source_file)
            # Rename the temp with the original file
            os.rename(edited_file, source_file)
    except IOError:
        print 'Sorry. Could not open the file. Please go to default_config and enter the data manually'
예제 #25
0
파일: users.py 프로젝트: mikson60/playtech
    def run(self):
        email            = prompt('Email')
        password         = prompt_pass('Password')
        password_confirm = prompt_pass('Confirm Password')
        first_name       = prompt('First name')
        last_name        = prompt('Last name')

        data             = MultiDict(dict(email=email, password=password,
                                          password_confirm=password_confirm,
                                          first_name=first_name,
                                          last_name=last_name))
        form             = RegisterForm(data, csrf_enabled=False)

        if form.validate():
            user = _datastore.create_user(email=email,
                                          password=encrypt_password(password),
                                            first_name=first_name,
                                            last_name=last_name, active=True,
                                            confirmed_at=datetime.datetime.utcnow())
            get_or_create_role = _datastore.find_or_create_role("ADMIN")
            _datastore.add_role_to_user(user, get_or_create_role)
            _datastore.commit()

            print('\nUser created successfully')
            print('User(id=%s email=%s)' % (user.id, user.email))
            return

        print('\nError creating user:'******'\n'.join(errors))
예제 #26
0
    def run(self):
        email = prompt('Enter email of user to be refreshed or \'all\' to ' +
                       'refresh for everyone')
        task_file = prompt('Input customized task file (e.g. ' +
                           './ladymarry/data/export_task_data.csv ' +
                           'or press Enter space to use default data')
        task_file = (task_file if task_file.strip()
                     else current_app.config['TASK_DATA_FILE'])

        if email == 'all':
            # Delete all tasks.
            for user in users.all():
                for task in user.tasks:
                    tasks.delete(task)

            # Refresh data for each user.
            for user in users.all():
                schedulers.schedule_tasks(user, task_file=task_file)
        else:
            u = users.first(email=email)
            if not u:
                print 'Invalid email.'
                return
            for task in u.tasks:
                tasks.delete(task)
            schedulers.schedule_tasks(u, task_file=task_file)

        print 'Success!'
예제 #27
0
    def run(self, addroles=True, revision='head', default=False):
        # migrate database to latest revision
        logger.info('Upgrading DB')
        upgrade(revision=revision)

        if addroles:
            logger.info('Inserting Roles into DB')
            Role.insert_roles()

        admin_role = Role.query.filter_by(name='Administrator').one()

        if default:
            admin_email = current_app.config.get('ADMIN_EMAIL',
                                                 '*****@*****.**')
        else:
            admin_email = prompt('Admin email', default='*****@*****.**')

        existing = User.query.filter(User.email == admin_email).scalar()
        while existing:
            print(
                'Email already registered. Please provide a different email address'
            )
            admin_email = prompt('Admin email', default='*****@*****.**')
            existing = User.query.filter(User.email == admin_email).scalar()

        admin = User(email=admin_email)

        if default:
            admin.password = '******'
        else:
            admin.password = prompt_pass('Admin password')

        db.session.add(admin)
        db.session.commit()
예제 #28
0
 def run(self):
     name = prompt("Role name")
     description = prompt("Role description")
     role = roleService.create(name=name, description=description)
     print '\nRole created successfully'
     print 'Role(id=%s name=%s)' % (role.id, role.name)
     return
예제 #29
0
 def run(self):
     print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
     print 'WARNING!!!!! YOU ARE ABOUT TO DELETE ALL ISSUES!!!!!'
     print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
     c = prompt_bool('Are you sure you wish to continue?')
     if c:
         email = prompt('Enter your administrator email address: ')
         u = User.query.filter_by(email=email).first()
         if u and u.has_role('super'):
             password = prompt('Enter password: '******'Deleting `issue_creators` table'
                 db.engine.execute(issues_creators.delete())
                 print 'Deleting `issues_bundles` table'
                 db.engine.execute(issues_bundles.delete())
                 print 'Deleting `Issue Covers` table'
                 IssueCover.query.delete()
                 print 'Deleting all objects from `Issues` table'
                 Issue.query.delete()
                 db.session.commit()
                 print 'All Issues have been deleted.'
                 print 'You should delete the cover images from the store!'
             else:
                 print 'Incorrect password, Aborting...'
         else:
             print 'User not found or is not an administrator, Aborting...'
     else:
         print 'Aborting...'
         return
예제 #30
0
    def run(self):
        name = prompt('Name')
        hostname = prompt('Hostname')

        try:
            deployment = models.Deployment.objects.get(name=name)
        except models.Deployment.DoesNotExist:
            deployment = models.Deployment(name=name).save()

        deployment.update(add_to_set__hostnames=hostname.strip())

        # create permissions
        models.Need.objects.create(action='view_events', deployment=deployment)
        models.Need.objects.create(action='view_participants',
                                   deployment=deployment)
        models.Need.objects.create(action='view_messages',
                                   deployment=deployment)
        models.Need.objects.create(action='view_process_analysis',
                                   deployment=deployment)
        models.Need.objects.create(action='view_result_analysis',
                                   deployment=deployment)
        models.Need.objects.create(action='view_quality_assurance',
                                   deployment=deployment)
        models.Need.objects.create(action='view_forms', deployment=deployment)

        models.Need.objects.create(action='add_submission',
                                   deployment=deployment)

        models.Need.objects.create(action='edit_forms', deployment=deployment)
        models.Need.objects.create(action='edit_locations',
                                   deployment=deployment)
        models.Need.objects.create(action='edit_participant',
                                   deployment=deployment)
        models.Need.objects.create(action='edit_submission',
                                   deployment=deployment)
        models.Need.objects.create(action='edit_both_submissions',
                                   deployment=deployment)
        models.Need.objects.create(action='edit_submission_quarantine_status',
                                   deployment=deployment)
        models.Need.objects.create(
            action='edit_submission_verification_status',
            deployment=deployment)

        models.Need.objects.create(action='import_participants',
                                   deployment=deployment)
        models.Need.objects.create(action='import_locations',
                                   deployment=deployment)

        models.Need.objects.create(action='export_participants',
                                   deployment=deployment)
        models.Need.objects.create(action='export_messages',
                                   deployment=deployment)
        models.Need.objects.create(action='export_submissions',
                                   deployment=deployment)
        models.Need.objects.create(action='export_locations',
                                   deployment=deployment)

        models.Need.objects.create(action='send_messages',
                                   deployment=deployment)
예제 #31
0
파일: database.py 프로젝트: taeram/aflutter
def setup():
    """ Populate the database with some defaults """
    if prompt_bool("Do you want to add an admin user?"):
        name = prompt("Username for admin")
        password = prompt("Password for admin")
        user = User(name=name, password=password, role="admin")
        db.session.add(user)
        db.session.commit()
예제 #32
0
 def run(self):
     name = prompt('Role Name')
     description = prompt('Role Description')
     _security_datastore = LocalProxy(
         lambda: current_app.extensions['security'].datastore)
     _security_datastore.create_role(name=name, description=description)
     db.session.commit()
     return
예제 #33
0
    def run(self):
        title = prompt('title')
        category = prompt('category in number')
        task_date = prompt('task_date')

        new_task = tasks.create(
            title=title, category=category, task_date=task_date)
        print 'Task created.'
예제 #34
0
파일: run.py 프로젝트: zhongmoxi/flask
def syncdb():
    from myflaskr.models import db, User
    db.create_all()
    name = prompt("Enter user name")
    password = prompt("Enter password")
    user = User.create(name, password)
    db.session.add(user)
    db.session.commit()
예제 #35
0
    def run(self):
        from_user = _get_user("from username", password=True)
        to_user = _get_user("to username", password=False)
        lat = float(prompt("lat"))
        lng = float(prompt("lng"))

        sup = Sup(from_user, to_user, lat, lng)
        db.session.add(sup)
        db.session.commit()
예제 #36
0
파일: manage.py 프로젝트: clww/excerpt-be
def create_user():
    username = prompt('Enter the username: '******'Enter the password for the user: '******'Enter the email: ')
    #username = '******'
    #password = '******'
    #email = '*****@*****.**'
    create_new_user(username=username,
            password=password, email=email)
예제 #37
0
def create_user(username=None, password=None, email=None):
    """Creates a normal user"""

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

    create_normal_user(username=username, password=password, email=email)
예제 #38
0
파일: manage.py 프로젝트: xuemy/flaskbb
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)
예제 #39
0
 def _prompt_password(self):
     default_password = "******"
     password = prompt("Password(default: %s):" % default_password,
                       default=default_password)
     confirm_password = prompt("Confirm Password:"******"password")
     if not password == confirm_password:
         print "Sorry, passwords did not match. Try again"
         self._prompt_password()
     return password, confirm_password
예제 #40
0
    def run(self):
        name = prompt('Name')
        hostname = prompt('Hostname')

        try:
            deployment = models.Deployment.objects.get(name=name)
        except models.Deployment.DoesNotExist:
            deployment = models.Deployment(name=name).save()

        deployment.update(add_to_set__hostnames=hostname.strip())
예제 #41
0
 def run(self):
     journal = find_journal()
     if not journal:
         print 'Invalid journal'
         return
     type = prompt('Type')
     path = prompt('Path')
     path = paths.create(type=type, path=path, journal_id=journal.id)
     print '\nPath created successfully'
     print 'Path(id=%s)' % (path.id)
예제 #42
0
 def run(self):
     journal = find_journal()
     if not journal:
         print 'Invalid journal'
         return
     type = prompt('Type')
     path = prompt('Path')
     path = paths.create( type = type, path = path, journal_id = journal.id )
     print '\nPath created successfully'
     print 'Path(id=%s)' % (path.id)
예제 #43
0
    def run(self):
        name = prompt('Name')
        hostname = prompt('Hostname')

        try:
            deployment = models.Deployment.objects.get(name=name)
        except models.Deployment.DoesNotExist:
            deployment = models.Deployment(name=name).save()

        deployment.update(add_to_set__hostnames=hostname.strip())
예제 #44
0
    def run(self):
        local_config_exists = os.path.isfile('local_config.py')
        if local_config_exists:
            if not prompt_bool("Overwrite existing settings?"):
                return

        admin_username = prompt('Choose an admin user name')
        admin_pass = prompt_pass('Choose an admin password')
        email_address = prompt('What email address do you want to send alerts to?')
        time_zone = prompt('What time zone are we in?', default='Europe/London')
        database_name = prompt_pass('Choose a database name', default='habitat')
예제 #45
0
 def run(self, **kwargs):
     #check if admin exists
     a = Role.objects.filter(name='admin').first()
     if a == None:
         Role(name='admin').save()
         u = prompt('Admin Email?', default='*****@*****.**')
         p = prompt('Admin Password (min 6 characters)?', default='enferno')
         CreateUserCommand().run(email=u, password=p, active=1)
         AddRoleCommand().run(user_identifier=u, role_name='admin')
     else:
         print 'Seems like an Admin is already installed'
예제 #46
0
def create_user(name='', username='', password=''):
    if not name:
        name = prompt('Enter name: ')
    if not username:
        username = prompt('Enter username: '******'Enter password: '******'User registered.'
예제 #47
0
 def run(self, **kwargs):
     #check if admin exists
     a = Role.objects.filter(name='admin').first()
     if a == None:
         Role(name='admin').save()
         u = prompt('Admin Email?',default='*****@*****.**')
         p = prompt('Admin Password (min 6 characters)?',default='enferno')
         CreateUserCommand().run(email=u,password=p,active=1)
         AddRoleCommand().run(user_identifier=u,role_name='admin')
     else:
         print 'Seems like an Admin is already installed'
예제 #48
0
 def run(self):
     title = prompt('Title')
     short_title = prompt('Short title')
     url = prompt('URL')
     journal = journals.create(title=title,
                               short_title=short_title,
                               url=url,
                               last_checked=datetime.datetime.utcnow(),
                               next_check=datetime.datetime.utcnow(),
                               metadata_update=datetime.datetime.utcnow())
     print '\nJournal created successfully'
     print 'Journal(id=%s title=%s)' % (journal.id, journal.title)
예제 #49
0
파일: manage.py 프로젝트: vanpav/top-24.su
    def _create_super_user(self):
        admin_role = self._create_role('admin', 'Admin role')

        username = prompt('Admin username')
        email = prompt('Admin email')
        while app.user_datastore.find_user(email=email) is not None:
            print 'Admin with email %s already exists' % email
            email = prompt('Admin email')
        password = prompt('Admin password')
        app.user_datastore.create_user(name=username,
                                       email=email,
                                       password=encrypt_password(password),
                                       roles=[admin_role])
예제 #50
0
 def run(self, **kwargs):
     db.create_all()
     # check if admin exists
     a = Role.query.filter_by(name='admin').first()
     if a is None:
         db.session.add(Role(name='admin'))
         db.session.commit()
         u = prompt('Admin Email?', default='*****@*****.**')
         p = prompt('Admin Password (min 6 characters)?', default='enferno')
         CreateUserCommand().run(email=u, password=p, active=1)
         AddRoleCommand().run(user_identifier=u, role_name='admin')
     else:
         print 'Seems like an Admin is already installed'
예제 #51
0
def adduser():
    """Add a new user to the system"""
    print("Adding new user:"******"Real name")
    admin_login = prompt("Username")
    admin_pass = prompt_pass("Password")
    if admin_real_name is not None and admin_login is not None and admin_pass is not None:
        admin_hashed_pw = pbkdf2_sha256.encrypt(admin_pass, rounds=200000, salt_size=16)
        u = User(admin_real_name, admin_login, admin_hashed_pw, ["user"])
        db.session.add(u)
        db.session.commit()
    else:
        print("The provided data was invalid.")
예제 #52
0
    def run(self, name=None, description=None):
        if not name:
            name = prompt("Role Name")

        if not description:
            description = prompt("Role description")

        if all([name, description]):
            role = Role.objects.create(name=name, description=description)
        else:
            role = "Cant create the role"

        print(role)
예제 #53
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
예제 #54
0
 def run(self):
     email = prompt('Email')
     password = prompt_pass('Password')
     password_confirm = prompt_pass('Confirm Password')
     active = bool(prompt('Actvice immediately', default='True'))
     role = prompt('Role', default='admin')
     if password == password_confirm:
         user = User(email=email,
                     password=hash_password(password),
                     confirmed_at=now(),
                     active=active,
                     role=role)
         db.session.add(user)
         db.session.commit()
예제 #55
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")
예제 #56
0
    def run(self):
        local_config_exists = os.path.isfile('local_config.py')
        if local_config_exists:
            if not prompt_bool("Overwrite existing settings?"):
                return

        admin_username = prompt('Choose an admin user name')
        admin_pass = prompt_pass('Choose an admin password')
        email_address = prompt(
            'What email address do you want to send alerts to?')
        time_zone = prompt('What time zone are we in?',
                           default='Europe/London')
        database_name = prompt_pass('Choose a database name',
                                    default='habitat')
예제 #57
0
 def run(self):
     from flask_security.utils import encrypt_password
     email = prompt('email')
     full_name = prompt('full name')
     password = prompt_pass('password')
     if not User.objects.filter(email=email).first():
         user = user_datastore.create_user(
             email=email,
             password=encrypt_password(password),
             full_name=full_name)
         user_role = user_datastore.find_or_create_role('USER')
         user_datastore.add_role_to_user(user, user_role)
         user.save()
     else:
         print("User with email:", email, "already exists")
예제 #58
0
 def run(self):
     diamond_id = prompt('Issue Diamond id')
     issue = Issue.query.filter_by(diamond_id=diamond_id).first()
     if issue:
         url = prompt('Url of jpg image for cover image')
         overwrite = False
         if issue.cover_image.original:
             print 'Issue object already has a cover image set.'
             overwrite = prompt_bool('Overwrite existing picture?')
         success = issue.set_cover_image_from_url(url, overwrite=overwrite)
         if success:
             print 'Successfully set cover image'
         return
     print 'No issue found!'
     return
예제 #59
0
def mailall():
    "Sends an email to all users"

    subject = prompt("Subject")
    message = prompt("Message")
    from_address = prompt("From", default="*****@*****.**")
    if prompt_bool("Are you sure ? Email will be sent to everyone!"):
        with mail.connect() as conn:
            for user in User.query:
                message = Message(subject=subject,
                                  body=message,
                                  sender=from_address,
                                  recipients=[user.email])

                conn.send(message)