Example #1
0
def signup():
    if request.method == "POST":
        names = request.form['names']
        email = request.form['email']
        password = request.form['password']
        User.create(names=names, email=email, password=password)
        return redirect(url_for('login'))
    # flash("You have successfully registered. Now login with your email and password!")
    return render_template('signup.html')
Example #2
0
def registration(login: hug.types.text, password: hug.types.text):

    if len(password) >= 6:
        password = hashlib.sha1(password.encode()).hexdigest()
    else:
        raise HTTPError(HTTP_422)

    token = uuid.uuid4().hex
    token = Token.create(token=token)
    try:
        User.create(**locals())
    except peewee.IntegrityError:
        token.delete()
        raise HTTPError(HTTP_409)
    return {'status': 'ok'}
Example #3
0
def host_signup(
        email: str,
        password: str,
        name: str,
        primary_affiliation: int,
        reason: str = None
) -> Tuple[Optional['UserData'], Optional[str], bool]:
    with session_scope() as session:
        if PrimaryAffiliation.get_by_id(session,
                                        primary_affiliation) is not None:
            user = User.create(
                session,
                User(email=email,
                     password=password,
                     name=name,
                     primary_affiliation=primary_affiliation))
            if user is not None:
                code = None
                threshold = int(get_property('user.threshold'))
                if threshold > 0:
                    code = UserVerification.add(session, user.id).code
                    set_property('user.threshold', str(threshold - 1))
                host_request = UserHostRequest(
                    user=user.id,
                    primary_affiliation=primary_affiliation,
                    reason=reason)
                session.add(host_request)
                return UserData(user), code, True
            return None, None, True
    return None, None, False
Example #4
0
def join():
	if request.method == 'GET':
		return render_template('join.html')
	username = request.form.get('username')
	password = request.form.get('password')
	email = request.form.get('email')
	if not username:
		flash('Please input username')
            	return redirect(url_for('join'))
	elif not password:
		flash('Please input password')
            	return redirect(url_for('join'))
	elif not email:
		flash('Please input email')
            	return redirect(url_for('join'))
        try:
         	# use the .get() method to quickly see if a user with that name exists
           	user = User.get(username=username)
            	flash('That username is already taken')
	except User.DoesNotExist:
           	# if not, create the user and store the form data on the new model
            	user = User.create(username=username,
			password=md5(password).hexdigest(),	
			email=email,join_date=datetime.datetime.now())
            		# mark the user as being 'authenticated' by setting the session vars
           	auth_user(user)
            	return redirect(url_for('homepage'))
Example #5
0
def new_user():
    if not request.is_json:
        abort(400)

    username = request.json.get('username')
    password = request.json.get('password')

    if not (username and password):
        return make_response(jsonify({'error': 'Username and password are required'}), 400)

    try:
        User.create(username, password)
    except AlreadyExist:
        return make_response(jsonify({'error': 'Username already taken'}), 409)

    return make_response(jsonify({'message': 'User successfully created', 'username': username}), 201)
Example #6
0
def get_user(sender_messenger_id):
    try:
        user = User.select().where(
            User.messenger_id == sender_messenger_id).get()
        return user
    except:
        user = User.create(messenger_id=sender_messenger_id,
                           new_user=True,
                           state='sign_up')
        return user
Example #7
0
def oauth():
    resp = openstreetmap.authorized_response()
    if resp is None:
        return 'Denied. <a href="' + url_for('login') + '">Try again</a>.'
    session['osm_token'] = (
            resp['oauth_token'],
            resp['oauth_token_secret']
    )
    user_details = openstreetmap.get('user/details').data
    uid = int(user_details[0].get('id'))
    session['osm_uid'] = uid
    try:
        User.get(User.uid == uid)
    except User.DoesNotExist:
        User.create(uid=uid)

    if session.get('next'):
        redir = session['next']
        del session['next']
    else:
        redir = url_for('front')
    return redirect(redir)
Example #8
0
def create_profile(request):
    """
    >>> tornadotesting.run(create_profile, fields={'username': '******'})
    'You created a user called alice'
    """
    user_data = {}
    user_data["username"] = request.get_field("username")
    user_data["password"] = request.get_field("password")
    user_data["description"] = request.get_field("description")
    user_data["location"] = request.get_field("location")
    user_data["birthdate"] = request.get_field("birthdate")
    user_data["image"] = request.get_field("image")
    #print(user_data)

    user = User.create(**user_data)
    request.write("You created a user called {}".format(user.username))
Example #9
0
def update_user_list(users):
    """Give a list of users in JSON format, create or update user profiles in the database."""
    for user_data in users['members']:
        user = User.get_or_none(slack_id=user_data.get('id'))
        if user is None:
            user = User.create(
                name=user_data.get('name'),
                display_name=user_data.get('profile').get('display_name'),
                slack_id=user_data.get('id'),
                is_bot=user_data.get('is_bot'),
                is_deleted=user_data.get('deleted'))
        else:
            user.name = user_data.get('name')
            user.display_name = user_data.get('profile').get('display_name')
            user.is_bot = user_data.get('is_bot')
            user.is_deleted = user_data.get('deleted')
            user.save()
Example #10
0
def response_handler(request):
    # Parse request and get the data we want out of it like messenger_id, text
    messenger_parser = MessengerParser(request)

    # Get user object from database so we can see the state of our user.
    try:
        user = User.select().where(
            User.messenger_id == messenger_parser.messenger_id).get()
    except:
        # If user doesn't exist, we create them. This would be a first time user.
        user = User.create(messenger_id=messenger_parser.messenger_id,
                           state='start',
                           score=0)

    # Here we need to decide what we need to do next for our user
    if user.state == 'start':
        # generic intro
        start(messenger_parser, user)
    elif user.state == 'question1':
        question1(messenger_parser, user)
    elif user.state == 'question2':
        question2(messenger_parser, user)
    elif user.state == 'question3':
        question3(messenger_parser, user)
    elif user.state == 'question4':
        question4(messenger_parser, user)
    elif user.state == 'question5':
        question5(messenger_parser, user)
    elif user.state == 'question6':
        question6(messenger_parser, user)
    elif user.state == 'question7':
        question7(messenger_parser, user)
    elif user.state == 'question8':
        question8(messenger_parser, user)
    elif user.state == 'question9':
        question9(messenger_parser, user)
    elif user.state == 'question10':
        question10(messenger_parser, user)
    else:
        results_handler(messenger_parser, user)

    # return the response to Facebook.
    return response()
Example #11
0
def cas_handler():
    service = request.args.get('service')
    ticket = request.args.get('ticket')
    if service == None or ticket == None:
        return redirect('http://home.ustc.edu.cn/~pengdinglan/cas_market/',
                        code=302)
    service = urllib.parse.quote(service, safe='')
    ticket = urllib.parse.quote(ticket, safe='')
    request_url = 'https://passport.ustc.edu.cn/serviceValidate?ticket=%s&service=%s' % (
        ticket, service)
    validate_res = str(urllib.request.urlopen(request_url).read())
    if validate_res.find('not recognized') != -1:
        return render_template('cas_failed.html',
                               msg='登陆失败,请稍后再试',
                               active='cas')
    re_user = re.compile('<cas:user>(.*)</cas:user>')
    m = re_user.search(validate_res)
    if not m:
        return render_template('cas_failed.html',
                               msg='登陆失败,请稍后再试',
                               active='cas')
    student_id = m.group(1)
    if student_id[0] not in ['p', 'P']:
        return render_template('cas_failed.html', msg='请使用学号登陆', active='cas')
    student_id = student_id.upper()
    try:
        user = User.get(User.student_id == student_id)
        login_user(user)
        if not user.has_registered:
            return redirect('/register', code=302)
        else:
            return redirect('/myitems', code=302)
    except DoesNotExist:
        user = User.create(name='',
                           student_id=student_id,
                           phone='',
                           is_admin=False,
                           has_registered=False)
        user.save()
        login_user(user)
        return redirect('/register', code=302)
Example #12
0
def response_handler(request):
     # Parse request and get the data we want out of it like messenger_id, text, and coordinates.
    messenger_parser = MessengerParser(request)

    # Get user object from database so we can see the state of our user.
    try:
        user = User.select().where(User.messenger_id == messenger_parser.messenger_id).get()
    except:
        # If user doesn't exist, we create them. This would be a first time user.
        user = User.create(messenger_id=messenger_parser.messenger_id, state='ask_type')
        
    # Here we need to decide what we need to do next for our user
    if user.state == 'ask_type':
        # ask user what genre
        type_handler(messenger_parser, user)
    else:
        # call api and get results
        results_handler(messenger_parser, user)

    # return the response to Facebook.
    return response()
Example #13
0
def provision(key):
    try:
        key = ProvisioningKey.get(ProvisioningKey.key == key)
    except DoesNotExist:
        abort(404)

    if request.method == 'GET':
        api_key = str(hexlify(urandom(16)), 'utf8').upper()
        return render_template('provision.html', api_key=api_key)
    elif request.method == 'POST':
        if 'username' not in request.form or 'api_key' not in request.form:
            return jsonify(**{'error': 'missing required form field'})

        try:
            user = User.create(username=request.form['username'],
                               api_key=request.form['api_key'])
            key.delete_instance()
        except IntegrityError:
            return jsonify(**{'error': 'duplicate username or API key'})

        return redirect(
            url_for('frontend.provision_sharex', api_key=user.api_key))
Example #14
0
def signup(email: str,
           password: str,
           name: str = None) -> Tuple[Optional['UserData'], Optional[str]]:
    """
    Sign user up with
    :param email:
    :param password:
    :param name:
    :return:
    """
    with session_scope() as session:
        user = User.create(session, User(email=email, password=password))
        if user is not None:
            code = None
            threshold = int(get_property('user.threshold'))
            if threshold > 0:
                logging.info("passed threshold")
                code = UserVerification.add(session, user.id).code
                set_property('user.threshold', str(threshold - 1))
            else:
                logging.info("failed threshold")
            return UserData(user), code
    return None, None
Example #15
0
    def create_user(self, **kwargs):
        username = kwargs.get('username', self.username)
        password = kwargs.get('password', self.password)

        return User.create(username, password)
Example #16
0
def create_user(user_id, social_id):
    return User.create(social_id=social_id, username=user_id, role='user', is_active=True)