Ejemplo n.º 1
0
def register():
	data = request.get_data()
	data = json.loads(data)

	print("Registering new user:"******""

	# check if username already exists
	if users.valid_user(data['username']):
		msg += "username "

	# confirm id hasn't already been used
	if data['user'] != '' and users.valid_id(data['user']):
		msg += "user "

	# if error return message
	if len(msg) > 0:
		return msg 						 			# return errors
	else:
		users.create_user(data)								# add to database
		session['username'] = data['username'] 						# log user in
		setUpTables(); 									# need to refresh the tables
		updateSession() 								# update session variables
		return "success"							        # return success
Ejemplo n.º 2
0
def signup():
    form = UserForm()
    error = None
    if request.method == 'POST' and form.validate():
        firstname = form.firstname.data
        middlename = form.middlename.data
        lastname = form.lastname.data
        street = form.street.data
        district = form.district.data
        city = form.city.data
        state = form.state.data
        country = form.country.data
        username = form.username.data
        password = form.password.data
        conf_pass = form.conf_pass.data
        mobileno = form.mobile.data
        # check duplicate
        result = s.query(Person).filter(Person.firstname == \
            firstname, Person.middlename == middlename, \
            Person.lastname == lastname).count()
        if result == 0:
            create_user(s, firstname, middlename, lastname,\
                street, district, city, state, country,\
                username, password, mobileno)
            return redirect(url_for('signin'))
    return render_template("signup.html", form=form)
Ejemplo n.º 3
0
def talk_to_me():
    if request.method == 'GET':
        return render_template('talk_to_me.html')
    else:
        msg = ''
        m_user = request.form.get('m_user')
        m_secret = request.form.get('m_secret')
        guy = request.form.get('guy')
        message = request.form.get('message')
        m_list = request.form.get('m_list')

        user = request.form.get('user')
        secret = request.form.get('secret')
        new_password = request.form.get('new_password')
        listing = request.form.get('list')
        delete = request.form.get('deletion')

        print(m_user, m_secret, guy, message, m_list)
        print(user, secret, new_password, listing, delete)

        if delete == 'yes':
            u.delete_user(user, secret)
        if listing == 'yes':
            u.list_users()
        if m_list == 'yes':
            m.list_messages(m_user, m_secret)
        if message is not None:
            m.send_message(m_user, m_secret, guy, message)
        if user is not None:
            u.create_user(user, secret)
        if new_password is not None:
            u.edit_user(user, secret, new_password)

        return render_template('talk_to_me.html', msg=msg)
Ejemplo n.º 4
0
def register_user():
    """User registration"""

    # if it's a get - render registration form
    if request.method == "GET":
        """Shows new user a registration form"""

        return render_template('registration.html')

    # otherwise register user in db
    if request.method == "POST":
        """Checks db for user and adds user if new"""

        fname = request.form.get('fname')
        lname = request.form.get('lname')
        email = request.form.get("email")
        password = request.form.get("password")

        hashed_pass = pwd_context.hash(password)
        # check if user exists in db already
        # this would happen if they were added to a case
        # but haven't actually registered yet
        user_check = User.query.filter_by(email=email).first()

        # create user or update the existing unregistered
        create_user(user_check, email, fname, lname, hashed_pass)

        # send them to their own page
        return "Success"
Ejemplo n.º 5
0
def signup():
    error = users.check_signup_form_errors(request)
    if not error:
        users.create_user(request)
        flash('Your account has been created. Login now.')
    else:
        flash('ERROR! {}'.format(error))
    return redirect(url_for('index'))
Ejemplo n.º 6
0
def get_user():
    """
    Method for beginning the user conversation. The method introduces the bot and
    gets the user based on the name extracted
    :return: The user with which the system is conversing
    """

    curr_user = None
    # Create the dataset if it doesn't already exist
    if not os.path.exists("users.json"):
        users.create_user("root", "users.json")

    flag = -1

    while flag == -1:
        # Sentence tokenization on the initial response of the user following the introduction
        sentence_list = nltk.sent_tokenize(
            input("SillyBot:\n" + bot_responses["Introduction"][random.randint(
                0,
                len(bot_responses["Introduction"]) - 1)] + "\n" + "User: "******"SillyBot: Don't be Silly! Please enter a proper name")
            sentence_list = nltk.sent_tokenize(
                input("SillyBot: What is your name?\n\nUser: "******"users.json")

        # We parse the remaining sentences to extract any relevant user information and add that to the user
        curr_user = users.add_information_unlabelled(curr_user,
                                                     sentence_list[1:])

        # If the user already exists (based on the error code returned by the create_user method, we do the entire thing
        # again)
        if flag == -1:
            print(
                "SillyBot: I am a Silly bot! You have a name matching someone else.\n"
                "I can't remember two people with the same name!")

    # Return the current user
    return curr_user
Ejemplo n.º 7
0
def initialize(DB):
    """initialize the app"""
    # this is called before the app starts
    # we're using a separte function because it has hashing and checking
    admin='admin'
    password = token_generator()
    password = '******'
    u  = create_user(DB, username=admin,
                     password=password,
                     is_admin=True)
    if u:
        # replace with a randomization
        print('WRITE THIS DOWN!')
        print('Admin user created. username={} password={}'.format(admin, password))
        
    # These are the default HOME and ABOUT pages-- can be easily changed later.
    # will not overwrite existing home and about pages.
    p = DB.pages.find_one({'slug':'home'})
    if p is None:
        # create only if page IS NOT present
        DB.pages.insert_one({'slug':'home', 'title':'Home', 'owner':'admin',
                             'content':'<b>Welcome, please change me.</b>  I am the <i>default</i> Home page!', 
                             'is_markdown':False, 'owner':'admin', 'show_nav':True, 'is_published': True})
        print("default HOME page created")
    p = DB.pages.find_one({'slug':'about'})
    if p is None:
        DB.pages.insert_one({'slug':'about', 'title':'About', 'owner':'admin',
                             'content':'<b>Welcome</b>, please change me.  I am the <i>default</i> boilerplate About page.',
                             'is_markdown':False, 'owner':'admin', 'show_nav':True, 'is_published': True})
        print("default ABOUT page created")
        
    m = DB.meta.find_one({})
    if m is None:
        DB.meta.insert_one({'brand':'FlaskPress', 'theme':'default'})
    def do_POST(self):
        self._set_headers(201)
        content_len = int(self.headers.get('content-length', 0))
        post_body = self.rfile.read(content_len)

        # Convert JSON string to a Python dictionary
        post_body = json.loads(post_body)

        # Parse the URL
        (resource, id) = self.parse_url(self.path)

        # Initialize new resource
        new_resource = None

        if resource == "register":
            new_resource = create_user(post_body)

        if resource == "categories":
            new_resource = create_category(post_body)

        if resource == "comments":
            new_resource = create_comment(post_body)

        if resource == "posts":
            new_resource = create_new_post(post_body)

        if resource == "tags":
            new_resource = create_tag(post_body)

        self.wfile.write(f"{new_resource}".encode())
    def do_POST(self):
        self._set_headers(201)
        content_len = int(self.headers.get('content-length', 0))
        post_body = self.rfile.read(content_len)

        post_body = json.loads(post_body)

        (resource, id) = self.parse_url(self.path)

        new_resource = None

        # Add a new items to the list.
        if resource == "users":
            new_resource = create_user(post_body)
        if resource == "categories":
            new_resource = create_category(post_body)
        if resource == "tags":
            new_resource = create_tag(post_body)
        if resource == "posts":
            new_resource = create_post(post_body)
        if resource == "tagPosts":
            new_resource = create_tagPost(post_body)
        if resource == "reactions":
            new_resource = create_reaction(post_body)
        if resource == "subscriptions":
            new_resource = create_subscription(post_body)
        if resource == "reactionPosts":
            new_resource = create_reactionPost(post_body)

        # Encode the new object and send in response
        self.wfile.write(f"{new_resource}".encode())
Ejemplo n.º 10
0
def create_schema(version=latest_version, db=db):
    metadata = get_metadata(version=version, db=db)

    # Insure that our schema versioning table doesn't exist--
    # which also insures that we're not trying to provision over
    # an existing database, as we have an explicit upgrade
    # workflow.
    if metadata.tables['_schema_version'].exists():
        raise Exception("Database already provisioned")

    # Check to see if any tables already exist, which would mean
    # we're attempting to provision a database that contains some
    # other application's data.  If it contained our application's
    # data, the _schema_version table would exist!
    for table in metadata.sorted_tables:
        if table.exists():
            raise Exception("Table already exists: " + table.name)

    # Create all of our tables
    metadata.create_all(db)

    # Populate schema version
    version_table = metadata.tables['_schema_version']
    # TODO: do we need to check for success somehow?
    db.execute(version_table.insert().values(version=version))

    # Create the default admin user
    from users import create_user
    id = create_user('admin',
                     password='******',
                     commit_email='',
                     can_create_users=True,
                     can_create_repositories=True)
Ejemplo n.º 11
0
    def do_POST(self):
        self._set_headers(201)
        content_len = int(self.headers.get('content-length', 0))
        post_body = self.rfile.read(content_len)

        post_body = json.loads(post_body)

        (resource, id) = self.parse_url(self.path)

        new_item = None

        if resource == "login":
            new_item = check_user(post_body)
        elif resource == "register":
            new_item = create_user(post_body)

        elif resource == "posts":
            new_item = create_post(post_body)

        elif resource == "comments":
            new_item = create_comment(post_body)

        elif resource == "tags":
            new_item = create_tag(post_body)
        # elif resource == "reactions":
        #     new_item = create_reaction(post_body)
        elif resource == "subscriptions":
            new_item = create_subscription(post_body)
        elif resource == "categories":
            new_item = create_category(post_body)

        self.wfile.write(f"{new_item}".encode())
Ejemplo n.º 12
0
def create_schema(version=latest_version, db=db):
    metadata = get_metadata(version=version, db=db)

    # Insure that our schema versioning table doesn't exist--
    # which also insures that we're not trying to provision over
    # an existing database, as we have an explicit upgrade
    # workflow.
    if metadata.tables['_schema_version'].exists():
        raise Exception("Database already provisioned")

    # Check to see if any tables already exist, which would mean
    # we're attempting to provision a database that contains some
    # other application's data.  If it contained our application's
    # data, the _schema_version table would exist!
    for table in metadata.sorted_tables:
        if table.exists():
            raise Exception("Table already exists: " + table.name)

    # Create all of our tables
    metadata.create_all(db)

    # Populate schema version
    version_table = metadata.tables['_schema_version']
    # TODO: do we need to check for success somehow?
    db.execute(version_table.insert().values(version=version))

    # Create the default admin user
    from users import create_user
    id = create_user('admin', password='******', commit_email='', can_create_users=True, can_create_repositories=True)
Ejemplo n.º 13
0
    def do_POST(self):
        self._set_headers(201)
        content_len = int(self.headers.get('content-length', 0))
        post_body = self.rfile.read(content_len)

        post_body = json.loads(post_body)

        (resource, id) = self.parse_url(self.path)

        new_item = None

        # POST resource method logic
        if resource == "categories":
            new_item = create_category(post_body)
        elif resource == "tags":
            new_item = create_tag(post_body)
        elif resource == "post_tags":
            new_item = create_postTag(post_body)
        elif resource == "login":
            new_item = handleLogin(post_body)
        elif resource == "users":
            new_item = create_user(post_body)
        elif resource == "posts":
            new_item = create_post(post_body)
        elif resource == "comments":
            new_item = create_comment(post_body)
        # elif resource == " ":
        #   new_item = yourCreate_handler(post_body)
        #...

        self.wfile.write(f"{new_item}".encode())
def create_account():
    if request.method == 'GET':
        return render_template('landing.html',
                               messageStatus="",
                               loginStatus="")
    elif request.method == 'POST':
        username = request.form.get('e_mail')
        first_name = request.form.get('first_name')
        last_name = request.form.get('last_name')
        empty_value_check = users.check_new_user_first_last_and_user_name(
            username, first_name, last_name)
        if empty_value_check:
            return render_template('landing.html',
                                   messageStatus=empty_value_check,
                                   loginStatus="")
        elif users.this_user_exists_already(username):
            return render_template(
                'landing.html',
                messageStatus=messages.message_account_was_already_created,
                loginStatus="")
        else:
            user_create_successful = users.create_user(username, first_name,
                                                       last_name)
            if user_create_successful:
                return render_template(
                    'landing.html',
                    messageStatus=messages.message_account_is_created,
                    loginStatus="")
            else:
                return render_template(
                    'landing.html',
                    messageStatus=messages.message_error_creating_account,
                    loginStatus="")
Ejemplo n.º 15
0
def add_user():
    # retrieve the parameters from the request
    new_username = request.form['my_username']
    new_password = request.form['my_password']
    hashed_password = hashlib.sha256(new_password.encode('utf-8')).hexdigest()
    json_result = {}
    json_result['outcome'] = users.create_user(new_username, hashed_password)
    return Response(json.dumps(json_result), mimetype='application/json')
Ejemplo n.º 16
0
def create_user():
    if request.is_json():
        return 'Request type is not json'
    json_data = request.get_json()
    user_id = users.create_user(json_data)
    if user_id is None:
        return 'User not updated'
    return users.get_user(user_id)
Ejemplo n.º 17
0
def new_user():
    username = request.form["username"]
    password = request.form["password"]
    if (users.create_user(username, password)):
        message = "Tili luotu käyttäjälle " + username
        flash(message, 'success')
    else:
        flash("Tiliä ei voitu luoda. Käyttäjätunnus on jo käytössä.", 'danger')
    return redirect("/user")
Ejemplo n.º 18
0
def make_user():
    '''
    Create new users
    :return:
    '''
    if request.method == 'POST':
        email = str(request.form['email'])
        info = create_user(email)
    return render_template('pro.html',info=info)
Ejemplo n.º 19
0
def handler(event, context):
    print(event)
    payload = json.loads(event['body'])
    client_email = payload['email']
    data = payload['data']
    response = create_user(client_email, data)
    if response["statusCode"] == 200:
        notify_admin_of_new_client(client_email)
    return response
Ejemplo n.º 20
0
def handle_users():
    is_admin = current_user.has_group("admins")
    
    if request.method == "POST":
        action = get_dict_default(request.form, "action", "")
        name = get_dict_default(request.form, "user", "")
        pwd1 = get_dict_default(request.form, "password1", "")
        pwd2 = get_dict_default(request.form, "password2", "")
        groups = get_dict_default(request.form, "groups", "")
        
        if action == "create" or action == "update":
            if name != "" and pwd1 != "" and pwd2 != "":
                if (not is_admin) and (name != current_user.name):
                    flash("Operation permitted only to Administrators", "error")
                    return render_template("users.html", title=cfg_get("AppTitle"), users=get_users(is_admin))
                else:
                    if pwd1 != pwd2:
                        flash("Passwords are different!", "error")
                        return render_template("users.html", title=cfg_get("AppTitle"), users=get_users(is_admin))
                    else:
                        user = create_user(name, pwd1)
                        if is_admin:
                            grps = groups.split(',')
                            grps = map(stripstr, grps)
                        else:
                            grps = current_user.groups
                        for grp in grps:
                            user.add_group(grp)
                        add_or_modify_user(user)
                        if action == "create":
                            flash("User '%s' created" % name, "info")
                        else:
                            flash("User '%s' modified" % name, "info")
                        return render_template("users.html", title=cfg_get("AppTitle"), users=get_users(is_admin))
            else:
                flash("All fields must be compiled!", "error")
                return render_template("users.html", title=cfg_get("AppTitle"), users=get_users(is_admin))
        elif action == "delete":
            if name != "":
                if (not is_admin) and (name != current_user.name):
                    flash("Operation permitted only to Administrators", "error")
                    return render_template("users.html", title=cfg_get("AppTitle"), users=get_users(is_admin))
                else:
                    del_user(name)
                    flash("User '%s' deleted" % name, "info")
                    return render_template("users.html", title=cfg_get("AppTitle"), users=get_users(is_admin))
            else:
                flash("User name missing!" % name, "error")
                return render_template("users.html", title=cfg_get("AppTitle"), users=get_users(is_admin))
        else:
            return ("Internal Server Error", 500, {})
    else:
        return render_template("users.html", title=cfg_get("AppTitle"), users=get_users(is_admin))
Ejemplo n.º 21
0
def create_user():
    if request.method == "GET":
        return render_template("new-user.html")
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        password_2 = request.form["password_check"]
        role = request.form["role"]
        create_ok, msg = users.create_user(username, password, password_2,
                                           role)
        if not create_ok:
            return render_template("new-user.html", error=msg)
        return render_template("success.html", msg=msg)
Ejemplo n.º 22
0
def register():
    name = request.form['fullName']
    email = request.form['email']
    mbti = request.form['mbti'].lower() # ensure it's lowercase
    password = request.form['password']

    # probably should be using try / except here instead of checking
    # if the return value is None
    user = create_user(name, email, mbti, password, g.db.cursor())
    if user == None:
        abort(400)
    else:
        return jsonify(user.serialize())
Ejemplo n.º 23
0
def register():
    if request.method == "GET":
        return render_template("new_user.html")
    if request.method == "POST":
        username = request.form["reg-username"]
        password = request.form["reg-password"]
        passwordAgain = request.form["reg-password_again"]
        if users.create_user(username, password, passwordAgain):
            return redirect("/")
        else:
            return render_template(
                "new_user.html",
                username=username,
                notification="Username already taken, or password mismatch")
Ejemplo n.º 24
0
def create_user():
    username = request.form["username"]
    password = request.form["password"]
    if len(username) < 2:
        flash("Ei kelvollinen käyttäjänimi")
        return redirect("/new_user")
    if len(password) < 6:
        flash("Liian lyhyt salasana.")
        return redirect("/new_user")
    if users.create_user(username, password):
        session["username"] = username
        return redirect("/")
    else:
        flash("Käyttäjän lisääminen epäonnistui.")
        return redirect("/new_user")
Ejemplo n.º 25
0
def add_user():
    if not request.user['can_create_users']:
        raise Exception("Permission denied; user cannot modify users.")
    for key in ['user_name', 'user_password', 'commit_name', 'commit_email']:
        if key not in request.form or len(request.form[key]) < 1:
            raise Exception(
                "User creation form requires field '{0}'".format(key))
    user_name = request.form['user_name']
    password = request.form['user_password']
    commit_name = request.form['commit_name']
    commit_email = request.form['commit_email']
    user_id = users.create_user(user_name,
                                password=password,
                                commit_name=commit_name,
                                commit_email=commit_email)
    # TODO: redirect to user details?
    return redirect(url_for('list_users'))
Ejemplo n.º 26
0
def create_user():
    identifier = request.form["identifier"]
    password = request.form["password"]
    print("creating identifier={} password={} ??".format(identifier, password))

    if users.has_user(hbase, identifier):
        message = "User {} already registered. Please login".format(identifier)
    else:
        if not users.create_user(hbase, identifier, password):
            message = "User {} not registered. Please retry".format(identifier)
        else:
            message = "User {} succesfully registered. Please login".format(identifier)

    print(message)

    out = render_template("user_message.html", message=message, do_popup=True, connected_user=connected_user)
    return out
Ejemplo n.º 27
0
def add_user():
    if not request.user['can_create_users']:
        raise Exception("Permission denied; user cannot modify users.")
    for key in ['user_name', 'user_password', 'commit_name', 'commit_email']:
        if key not in request.form or len(request.form[key]) < 1:
            raise Exception("User creation form requires field '{0}'"
                .format(key))
    user_name = request.form['user_name']
    password = request.form['user_password']
    commit_name = request.form['commit_name']
    commit_email = request.form['commit_email']
    user_id = users.create_user(
        user_name,
        password=password,
        commit_name=commit_name,
        commit_email=commit_email)
    # TODO: redirect to user details?
    return redirect(url_for('list_users'))
Ejemplo n.º 28
0
def create_user_and_download_tracks(username):
    username = username.lower()
    page_limit = int(request.args.get('page_limit', 5))
    user_details = fetch_last_fm_user(username)

    if not user_details:
        return "No user found", 404

    user = User.get_by_key_name(username)

    if not user:
        logger.info("Creating user %s" % username)
        user = create_user(username, user_details)

    logger.info("Scheduling track download for %s" % username)
    task_args = {"username": username, "page_limit": page_limit}
    task_path = '/api/download-played-tracks-worker'
    taskqueue.add(queue_name="download-played-tracks-push", url=task_path,  params=task_args)
    return json.dumps(user.to_dict())
Ejemplo n.º 29
0
def signup():
    if (request.args.get('email') and request.args.get('pw') and
        request.args.get('first_name') and request.args.get('last_name')):

        email = request.args.get('email')
        pw = request.args.get('pw')
        first_name = request.args.get('first_name')
        last_name = request.args.get('last_name')

        with db_conn() as conn:
            try:
                if users.create_user(conn, first_name, last_name, email, pw):
                    return redirect('/profile')
                return 'Unexpected error'
            except ValueError:
                return render_template('signup.html', title='Signup', error='User already exists!')
        return redirect('/profile')

    return render_template('signup.html', title='Signup')
Ejemplo n.º 30
0
def sign_up(conn, addr):
    success = False
    while not success:
        message = get_message(conn)
        #time.sleep(2)
        if not message:
            return False
        message = message[:-1].splitlines()
        if len(message) != 2:
            send_message(conn, "2")
            continue
        username, password = message
        print("receive username '%s' from %s\n" % (username, addr[0]))
        print("receive password '%s' from %s\n" % (password, addr[0]))
        success, message = users.create_user('sign up', username, password)
        send_message(conn, message)
        if success:
            print("%s successfully created user '%s'\n" % (addr[0], username))
    client_users[conn] = username
    success, message = users.login(username, password)
    return True
    def do_POST(self):
        self._set_headers(201)
        content_len = int(self.headers.get('content-length', 0))
        post_body = self.rfile.read(content_len)

        post_body = json.loads(post_body)

        (resource, id) = self.parse_url(self.path)

        new_comment = None
        new_category = None
        new_post = None
        new_tag = None
        new_user = None
        new_login = None

        if resource == "comments":
            new_comment = create_comment(post_body)
            self.wfile.write(f"{new_comment}".encode())

        if resource == "categories":
            new_category = create_category(post_body)
            self.wfile.write(f"{new_category}".encode())

        if resource == "posts":
            new_post = create_post(post_body)
            self.wfile.write(f"{new_post}".encode())

        if resource == "tags":
            new_tag = create_tag(post_body)
            self.wfile.write(f"{new_tag}".encode())

        if resource == "register":
            new_user = create_user(post_body)
            self.wfile.write(new_user.encode())

        if resource == "login":
            new_login = get_user_by_email_and_password(post_body)
            self.wfile.write(f"{new_login}".encode())
Ejemplo n.º 32
0
    def post(self, *args, **kwargs):
        login = request.json.get('login')
        password = request.json.get('password')
        confirmation = request.json.get('confirmation')

        if not all([login, password, confirmation]):
            return {
                'message': 'Login, password, confirmation fields required.'
            }, 400

        if password != confirmation:
            return {
                'message': 'Password and confirmation have to be equal.'
            }, 400

        if User.query.filter_by(login=login).first() is not None:
            return {'message': 'User with the same login already exists.'}, 400

        user = create_user(login, password)
        auth_token = user.encode_auth_token()

        return {'token': auth_token.decode('utf-8')}, 201
Ejemplo n.º 33
0
    def do_POST(self):
        # Set response code to 'Created'
        self._set_headers(201)
        content_len = int(self.headers.get('content-length', 0))
        post_body = self.rfile.read(content_len)

        # Convert JSON string to a Python dictionary
        post_body = json.loads(post_body)

        # Parse the URL
        (resource, id) = self.parse_url(self.path)

        # Initialize new item
        new_item = None

        if resource == "login":
            new_item = get_user_by_email(post_body)

        if resource == "register":
            new_item = create_user(post_body)

        if resource == "posts":
            if 'tag_id' in post_body:
                # Not updating post object so no need to put this call in PUT
                # For now, POST request in Postman only
                new_item = add_tag_to_post(post_body)
            else:
                new_item = create_post(post_body)
            # pass
        if resource == "categories":
            new_item = create_category(post_body)

        if resource == "tags":
            new_item = create_tag(post_body)

        if resource == "comments":
            new_item = create_comment(post_body)

        self.wfile.write(f"{new_item}".encode())
Ejemplo n.º 34
0
def create_user(context,galaxy,email,public_name,password,only_check,
                message_template):
    """
    Create new Galaxy user.

    Creates a new user in GALAXY, using EMAIL for the username.
    If PUBLIC_NAME is not supplied then it will be generated
    automatically from the leading part of the email address.

    If a password for the new account is not supplied using the
    --password option then nebulizer will prompt for one.
    """
    # Check message template is a .mako file
    if message_template:
        if not message_template.endswith(".mako"):
            logger.critical("Message template '%s' is not a .mako file"
                            % message_template)
            return 1
    # Get a Galaxy instance
    gi = context.galaxy_instance(galaxy)
    if gi is None:
        logger.critical("Failed to connect to Galaxy instance")
        return 1
    # Sort out email and public name
    if public_name:
        if not users.check_username_format(public_name):
            logger.critical("Invalid public name: must contain only "
                            "lower-case letters, numbers and '-'")
            return 1
    else:
        # No public name supplied, make from email address
        public_name = users.get_username_from_login(email)
    # Create user
    print "Email : %s" % email
    print "Name  : %s" % public_name
    return users.create_user(gi,email,public_name,password,
                             only_check=only_check,
                             mako_template=message_template)
Ejemplo n.º 35
0
def create_user():
	"""Route for create new user (register)"""

	user_data = {
		'username': request.form.get('username'),
		'password': request.form.get('password'),
		'email': request.form.get('email')
	}

	# Input validation
	# Regex pattern
	username_criteria = "^[a-zA-Z0-9_]{3,35}$"

	# Check if any field is null
	required = []
	for key, value in user_data.iteritems():
		if not value:
			required.append(key)

	if required:  # If any field is null
		return error_handlers.bad_request( (",").join(required) + " required")

	else:  # No one field is null

		# Check criteria
		if not re.search(username_criteria, user_data['username']):
			return error_handlers.bad_request(
				"Username must between 3-35 characters and "
				"can contain only [a-z] [A-Z] [0-9] and " 
				"undescore '_' "
				)

		elif len(user_data['password']) < 6:
			return error_handlers.bad_request("Password must have 6 characters")

		else:  # Input valid
			# Try create new user
			new_user_id = users.create_user(user_data)
			response={}
			
			if new_user_id:  # If success create new user
				links = '%s/%s' % (request.url, new_user_id)
				response['data'] = {
						'id' : new_user_id,
				        'type': 'users',
				        'attributes': user_data,
				        'links' : {
				        	'self': links
				        }
				}
				status = 201
			else:  # If failed create new user
				status = 202

			resp = jsonify(response)

			# Header JSONAPI
			resp.mimetype = 'application/vnd.api+json'  
			resp.location = links
			resp.status_code = status

			return resp
def test_insert_user_and_check_password():
    with app.app_context():
        users.create_user('*****@*****.**', 'test test', 'testewr')
        users.set_user_password('*****@*****.**', 'thepassword')
        assert users.password_and_username_ok('*****@*****.**', 'thepassword')
def test_insert_users(input_password, input_user_first_name,
                      input_user_last_name, input_email):
    with app.app_context():
        users.create_user(input_email, input_user_first_name,
                          input_user_last_name)
        users.set_user_password(input_email, input_password)
Ejemplo n.º 38
0
def manage_users(args=None):
    """
    Implements the 'manage_users' utility

    """
    deprecation_warning()
    if args is None:
        args = sys.argv[1:]

    p = base_parser(usage=\
                    "\n\t%prog list   GALAXY_URL [options]"
                    "\n\t%prog create GALAXY_URL EMAIL [PUBLIC_NAME]"
                    "\n\t%prog create GALAXY_URL -t TEMPLATE START [END]"
                    "\n\t%prog create GALAXY_URL -b FILE [options]",
                    description="Manage and create users in a Galaxy "
                    "instance")
    commands = ['list','create']

    # Get compulsory arguments
    if len(args) == 1:
        if args[0] == '-h' or args[0] == '--help':
            p.print_usage()
        elif args[0] == '--version':
            p.print_version()
        sys.exit(0)
    if len(args) < 2:
        p.error("need to supply a command and a Galaxy URL/alias")
    command = args[0]
    galaxy_url = args[1]

    # Setup additional command line options
    if command not in commands:
        p.error("unrecognised command: '%s'" % command)
    elif command == 'list':
        p.set_usage("%prog list GALAXY_URL [options]")
        p.add_option('--name',action='store',dest='name',default=None,
                     help="specific emails/user name(s) to list")
        p.add_option('-l',action='store_true',
                     dest='long_listing_format',default=False,
                     help="use a long listing format (include ids, "
                     "disk usage and admin status)")
    elif command == 'create':
        p.set_usage("\n\t%prog create GALAXY_URL EMAIL [PUBLIC_NAME]"
                    "\n\t%prog create GALAXY_URL -t TEMPLATE START [END]"
                    "\n\t%prog create GALAXY_URL -b FILE [options]")
        p.add_option('-p','--password',action='store',dest='passwd',
                     default=None,
                     help="specify password for new user account "
                     "(otherwise program will prompt for password)")
        p.add_option('-c','--check',action='store_true',dest='check',
                     default=False,
                     help="check user details but don't try to create "
                     "the new account")
        p.add_option('-t','--template',action='store_true',
                     dest='template',default=False,
                     help="indicates that EMAIL is actually a "
                     "'template' email address which includes a '#' "
                     "symbol as a placeholder where an integer index "
                     "should be substituted to make multiple accounts "
                     "(e.g. 'student#@galaxy.ac.uk').")
        p.add_option('-b','--batch',action='store_true',dest='batch',
                     default=False,
                     help="create multiple users reading details from "
                     "TSV file (columns should be: "
                     "email,password[,public_name])")
        p.add_option('-m','--message',action='store',
                     dest='message_template',default=None,
                     help="populate and output Mako template "
                     "MESSAGE_TEMPLATE")
        
    # Process remaining arguments on command line
    if args[1] in ('-h','--help','--version'):
        args = args[1:]
    else:
        args = args[2:]
    options,args = p.parse_args(args)
    handle_debug(debug=options.debug)
    handle_suppress_warnings(suppress_warnings=options.suppress_warnings)
    handle_ssl_warnings(verify=(not options.no_verify))

    # Handle password if required
    email,password = handle_credentials(options.username,
                                        options.galaxy_password,
                                        prompt="Password for %s: " % galaxy_url)

    # Get a Galaxy instance
    gi = get_galaxy_instance(galaxy_url,api_key=options.api_key,
                             email=email,password=password,
                             verify_ssl=(not options.no_verify))
    if gi is None:
        logger.critical("Failed to connect to Galaxy instance")
        sys.exit(1)

    # Execute command
    if command == 'list':
        users.list_users(gi,name=options.name,long_listing_format=
                         options.long_listing_format)
    elif command == 'create':
        # Check message template is .mako file
        if options.message_template:
            if not os.path.isfile(options.message_template):
                logger.critical("Message template '%s' not found"
                                % options.message_template)
                sys.exit(1)
            elif not options.message_template.endswith(".mako"):
                logger.critical("Message template '%s' is not a .mako file"
                                % options.message_template)
                sys.exit(1)
        if options.template:
            # Get the template and range of indices
            template = args[0]
            start = int(args[1])
            try:
                end = int(args[2])
            except IndexError:
                end = start
            # Create users
            retval = users.create_users_from_template(gi,template,
                                                      start,end,options.passwd,
                                                      only_check=options.check)
        elif options.batch:
            # Get the file with the user data
            tsvfile = args[0]
            # Create users
            retval = users.create_batch_of_users(gi,tsvfile,
                                                 only_check=options.check,
                                                 mako_template=options.message_template)
        else:
            # Collect email and (optionally) public name
            email = args[0]
            try:
                name = args[1]
                if not users.check_username_format(name):
                    logger.critical("Invalid name: must contain only "
                                    "lower-case letters, numbers and "
                                    "'-'")
                    sys.exit(1)
            except IndexError:
                # No public name supplied, make from email address
                name = users.get_username_from_login(email)
            # Create user
            print "Email : %s" % email
            print "Name  : %s" % name
            retval = users.create_user(gi,email,name,options.passwd,
                                       only_check=options.check,
                                       mako_template=options.message_template)