Пример #1
0
def user_pref_location(who, what, location):
    '''
    Recup le deuxième choix de l'user, 
    redirige vers /user_pref/<what>/<location>
    '''

    message = "Plutôt solo ou plutôt bain de foule?"

    if request.method == 'POST':
        print('Dans troisième choix')
        print(len(list(request.form.items())))
        for keys, val in request.form.items():
            print(keys, val)
            #what = {keys:val}
            animation = val
            print(f"animation = {animation}")
            user = User(id_=random.randint(0, 2500),
                        what=what,
                        location=location,
                        animation=animation)
            user.saveUser()
            return redirect(
                url_for("resultat",
                        who=who,
                        what=what,
                        location=location,
                        animation=animation,
                        user=user))

    return render_template('user_pref_location.html', message=message)
Пример #2
0
    def get(self, id):
        
        
        cur = self.db.cursor()
        user = None

        psycopg2.extras.register_uuid()
        try:

            cur.execute("SELECT * FROM public.users \
                          WHERE id = %s", (id,))

            row = cur.fetchone()
            # build the user object
            # get the user id & convert it to python UUID type

            user = User()
            user.id = row[0]
            user.name = row[1]
            user.email = row[2]
            user.password = row[3]

        except Exception as e:

            print "An error occurred while reading user id"
            print e
            raise e
        
        finally:
            # return user object
            cur.close()
            return user
Пример #3
0
def signup():
    if request.method == 'POST':
        app.logger.info("Request: %s" % request.get_json())
        user_details = request.get_json()
        user = User(user_details)
        status_code = 200
        try:
            new_user = user.create_user()
            response = {
                'authorized': True,
                'token': get_jwt(new_user),
                'email': new_user['email'],
                'first_name': new_user['first_name'],
                'last_name': new_user['last_name']
            }
        except UserAlreadyExists as e:
            status_code = 400
            response = {'authorized': False, 'message': str(e)}
        except UserCreateError as e:
            status_code = 500
            response = {'authorized': False, 'message': str(e)}
        except Exception as e:
            status_code = 500
            response = {
                'authorized': False,
                'message': str(e),
            }
    else:
        app.logger.info('No idea what this request is')
        status_code = 400
        response = {'authorized': False}
    return jsonify(response), status_code
Пример #4
0
async def spending(item: Item):
    """
    Make visualizations based on past spending 📊
    ### Request Body
    - `bank_account_id`: int
    - `graph_type`: str (pie or bar)
    - `time_period`: str (week, month, year, all)
    - `OPTIONAL: color_template`: [Color Template Options (Sequential only)](https://plotly.com/python/builtin-colorscales/#builtin-sequential-color-scales)
    - `OPTIONAL: hole`: float (0 - 1)
    ### Response
    - `plotly object`:
    visualizing the user's spending habits in the form of the selected graph
    type.
    """
    # Get the JSON object from the request body and cast it to a dictionary
    input_dict = item.to_dict()
    bank_account_id = input_dict['bank_account_id']
    graph_type = input_dict['graph_type']
    time_period = input_dict['time_period']
    color_template = input_dict['color_template']
    hole = input_dict['hole']

    transactions = load_user_data(bank_account_id)

    user = User(transactions, hole=hole)

    if graph_type == 'pie':
        return user.categorical_spending(time_period=time_period,
                                         color_template=color_template)

    if graph_type == 'bar':
        return user.bar_viz(time_period=time_period,
                            color_template=color_template)
Пример #5
0
    def setUp(self):
        self.user = User(
            'testuser',
            'password'
        )

        self.user.set_new_user()
Пример #6
0
def index():
    authenticated = flask_login.current_user.is_authenticated
    if authenticated:
        display = flask_login.current_user.display
        registered = flask_login.current_user.registered
        billable = flask_login.current_user.billable

        status = {
            'authenticated': authenticated,
            'registered': registered,
            'billable': billable
        }
        if registered == 200 and billable == 200:
            return flask.redirect(flask.url_for('user'))
        else:
            registration, billing = check_status(
                flask_login.current_user.access_token)
            User.update_status(flask_login.current_user.id, registration,
                               billing)
            return flask.render_template('index.html',
                                         display=display,
                                         status=status,
                                         CONFIG=CONFIG)
    else:
        status = {'authenticated': False, 'registered': 400, 'billable': 400}
        return flask.render_template('index.html',
                                     display='',
                                     status=status,
                                     CONFIG=CONFIG)
Пример #7
0
def test_get_non_existent_user(start_mongo_no_existing_collection_db):
    mongo_uri = 'mongodb://127.0.0.1:27017/'
    mongo_database = 'test_nhsdb'
    user = {'email': 'unknown_email@address', 'password': '******'}
    usr = User(user, mongo_uri, mongo_database)
    stored_user = usr.get_user_by_email()
    assert stored_user is None
Пример #8
0
class TestUser(unittest.TestCase):

    def setUp(self):
        self.user = User(
            'testuser',
            'password'
        )

        self.user.set_new_user()

    def tearDown(self):
        self.db = Database()
        self.db.make_query(
            '''
            DELETE FROM user WHERE username = "******"
            '''.format('testuser')
        )

    def test_check_username(self):
        self.assertTrue(
            self.user.check_username()
        )

    def test_check_password(self):
        self.assertTrue(
            self.user.check_password()
        )
Пример #9
0
def handle_user_get():
    """Returns an existing user or creates one"""
    try:
        auth0_id = g.user['sub']
        user = User(auth0_id)
        return user.dump()
    except Exception as e:
        return default_error_responce(e)
Пример #10
0
 def test_delete_all_contacts(self):
     with ContactManager() as cm:
         user0 = User("Mike", "13800000000")
         user1 = User("Mike", "13800000001")
         cm.new_contact(user0).new_contact(user1)
         self.assertEqual(cm.size(), 2)
     with ContactManager() as cm:
         cm.delete_all_contacts()
         self.assertEqual(cm.size(), 0)
Пример #11
0
def test_add_subscribers() -> None:
    channel_name = "chan1"
    subscribers = {User("u1"), User("u2")}
    channel = Channel(channel_name, subscribers)
    new_user = User("u3")
    channel.add_subscriber(new_user)
    returned_subscribers = channel.get_subscribers()
    subscribers.add(new_user)
    assert subscribers == returned_subscribers
Пример #12
0
 def add_test_user(self, username, password):
     """ adds a user to the database so that we can use it for testing
     """
     user = User(username, password)
     # delete the user if its already in the database
     # just to be sure that its not part of the last
     # unsucessful run
     user.delete_user()
     rv = user.add_user()
     assert rv
Пример #13
0
 def test_user_to_object(self):
   username = "******"
   phones = "13800000000"
   user = User(username,phones)
   user_object = user.to_object()
   self.assertDictEqual(user_object,{
     "index":-1,
     "username":user.username,
     "phones":user.phones
   })
Пример #14
0
def insertData(users, channels):
	db.create_all()

	ch = Channel()
	usr = User()
	ch.getChannelInfo()
	usr.getUserInformation()
	ch.sendChannelsToDatabase(True) 
	usr.sendUsersToDatabase(True)
	db.session.commit()  
Пример #15
0
def test_create_user(start_mongo_no_existing_collection_db):

    user = {'email': 'email@address', 'password': '******'}
    usr = User(user, mongo_uri, mongo_database)
    usr.create_user()
    with UserStore(mongo_uri, mongo_database) as user_store:
        stored_user = user_store.get_user(user)
        assert stored_user['email'] == user['email']
        assert stored_user['first_name'] == 'unknown first name'
        assert stored_user['last_name'] == 'unknown last name'
        assert len(stored_user['salt']) == 16
        assert stored_user.get('hash') is not None
Пример #16
0
 def test_search_contact_with_user_name(self):
     with ContactManager() as cm:
         user0 = User("Mike", "13800000000")
         user1 = User("Alice", "13100000000")
         cm.new_contact(user0)
         cm.new_contact(user1)
         matches = cm.search_contact(user0.username)
         self.assertEqual(len(matches), 1)
         self.assertEqual(matches[0]["username"], user0.username)
         matches = cm.search_contact("MIKE")
         self.assertEqual(len(matches), 1)
         self.assertEqual(matches[0]["username"].lower(), "MIKE".lower())
Пример #17
0
def registerSubmit():
    user = User()
    firstname = request.form["first_name"]
    lastname = request.form["last_name"]
    email = request.form["email"]
    password = request.form["password"]
    cursor = db.cursor()
    #generate password hash
    password = user.generatePasswordHash(password)
    cursor.execute("INSERT INTO users(first_name, last_name, email, password) VALUES (%s, %s, %s, %s)", (firstname, lastname, email, password))
    db.commit()
    return redirect("/login")
Пример #18
0
def main():
	ch = Channel()
	usr = User()
	channels = ch.getChannelInfo()
	people = usr.getUserInformation()
	#messagesForAllChannels = []
	#for chan in channels:
	#	mes =  getMessageinfo(chan)
	#	messagesForAllChannels.append(mes)


	insertData(people, channels)
Пример #19
0
def handle_user_delete():
    """Deletes an existing user"""
    try:
        auth0_id = g.user['sub']
        user = User(auth0_id, no_create=True)
        user.delete()
        extra_info = delete_auth0_user(auth0_id)
        return {'status': 'success', 'extra_info': extra_info}
    except UserNotFound as e:
        return user_not_found_responce(e)
    except Exception as e:
        return default_error_responce(e)
Пример #20
0
def test_subscriber_printer() -> None:
    channel_name = "chan1"
    subscribers = {User("u1"), User("u2")}
    channel = Channel(channel_name, subscribers)
    printer = SubscriberPrinter()
    captured_output = io.StringIO()
    sys.stdout = captured_output
    printer.on_video_published(channel)
    sys.stdout = sys.__stdout__
    output = captured_output.getvalue().split("\n")[:-1]
    assert len(output) == 2
    for name in output:
        assert name in ["u1", "u2"]
Пример #21
0
    def get_users(self):
        sql = "SELECT name, " \
              "AES_DECRYPT(password, '" + Security().key + "'), " \
                                                           "enabled, password_restriction, role FROM " \
              + self.database + '.' + self.users_table

        data = self.execute_sql(sql)
        all_users = [User(*user) for user in data]
        if len(all_users) == 0:
            user = User("admin", "admin", role='ADMIN')
            self.add_user(user)
            self.get_users()
        return all_users
async def future_budget(budget: Budget):
    """
    Suggest a budget for a specified user.

    ### Request Body
    - `bank_account_id`: int
    - `monthly_savings_goal`: integer

    ### Response
    - `category`: grandparent category name
    - `budgeted_amount`: integer suggesting the maximum the user should spend
    in that catgory next month

    """

    # Get the JSON object from the request body and cast it to a dictionary
    input_dict = budget.to_dict()
    bank_account_id = input_dict['bank_account_id']
    monthly_savings_goal = input_dict['monthly_savings_goal']

    transactions = load_user_data(bank_account_id)

    # instantiate the user and chooses category column
    # user = User(transactions, cat_column='grandparent_category_name')
    # user = User(transactions, cat_column='parent_category_name')
    user = User(transactions, cat_column='merchant_name')

    # predict budget using time series model
    pred_bud = user.predict_budget()

    # if a fatal error was encountered while generating the budget,
    # return no budget along with the warning list
    if user.warning == 2:
        return json.dumps([None, user.warning_list])

    # modify budget based on savings goal
    modified_budget = user.budget_modifier(
        pred_bud, monthly_savings_goal=monthly_savings_goal)

    # if a fatal error was encountered while modifying the budget,
    # return no budget along with the warning list
    if user.warning == 2:
        return json.dumps([None, user.warning_list])

    # if a non-fatal warning was encountered in predict_budget() or
    # budget_modifier(), return the budget along with the warning list
    elif user.warning == 1:
        return json.dumps([modified_budget, user.warning_list])

    return modified_budget
Пример #23
0
def login_post():
    form = LoginForm()
    if form.validate_on_submit():
        user = User(form.username.data)
        password = form.password.data

        if user is None or user.check_password(password) == False:
            flash('Invalid username or password')
            return redirect(url_for('login_get'))
        login_user(user)
        return redirect(url_for('message_get'))
    else:
        flash(parse_login_error(form.errors))
        return redirect(url_for('login_get'))
Пример #24
0
def oauth2callback():
    state = flask.session['state']
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(CLIENT_SECRETS_FILE,
                                                                   state=state,
                                                                   scopes=SCOPES)
    flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)

    credentials = dict_manager.Credentials.json_to_dictionary(flow.credentials.to_json())
    token = credentials['token']
    refresh = credentials['refresh_token']
    scopes = credentials['scopes']

    user_information = portal_requests.Launch.get_profile(token)
    unique_id = user_information['id']
    email = user_information['email']

    returning_user = User.get(unique_id)
    if not returning_user:
        registration, billing = check_status(token)
        User.create(unique_id, email, registration, billing, token, refresh, scopes)
    else:
        if not returning_user.registered == 200 or not returning_user.billable == 200:
            registration, billing = check_status(token)
            User.update_status(unique_id, registration, billing)
        User.update_tokens(unique_id, token, refresh, scopes)
    current_user = User.get(unique_id)

    flask_login.login_user(current_user)
    flask.flash('Logged in successfully')
    return flask.redirect(flask.url_for('index'))
Пример #25
0
def handle_user_patch():
    """Updates fields on a user"""
    req = request.json
    try:
        auth0_id = g.user['sub']
        remaining_fields = update_root_attributes(auth0_id, req['fields'])
        user = User(auth0_id, no_create=True)
        user.update(remaining_fields)
    except ValidationError as e:
        return ({'status': 'error', 'reason': str(e)}, 400)
    except KeyError as e:
        return ({'status': 'error', 'reason': f'cant save key {e}'}, 400)
    except UserNotFound as e:
        return user_not_found_responce(e)
    return {'status': 'success'}
Пример #26
0
def sign_up():
    username = input("SIGN UP: \n\tEnter your username: "******"\tEnter your password: ")

    user = User(username, password)
    store.add_user(user)  # could raise AssertionError if username exists
    print('Success, you can now login')
Пример #27
0
def initdb():
    """Init/reset database."""

    if not prompt_bool("Are you sure? You will lose all your data!"):
        return

    db.drop_all()
    db.create_all()

    demo = User(
        username=u'demo',
        email='*****@*****.**',
        password='******',
        role_id=USER,
        status_id=ACTIVE,
        user_detail=UserDetail(
            first_name=u'Demo',
            last_name=u'Dude',
            gender=u'female',
            dob=datetime.date(1985, 02, 17),
            phone=1234567890,
            bio=u'Demo dude is pretty sweet.',
            url=u'http://www.example.com/demo',
        ),
    )
Пример #28
0
def user_delete():
    if not request.json or 'user_id' not in request.json:
        return jsonify({"error": "bad request"}), 400
    user = User.user_delete(request.json['user_id'])
    if not user:
        return jsonify({"error": "access denied"})    
    return jsonify({"msg": msg})
Пример #29
0
    def get_user(uid, g_config):
        """
        Search user from DB, return the user object.
        :param g_config: 글로벌 콘피그 파일
        :param uid: User ID (Recipient ID)
        :return: User Object (없으면 None)
        """
        client = MongoClient()
        db = client['mealworm5']
        users = db.users

        usr = users.find_one({"uid": uid})
        if usr:
            return User({
                'uid': uid,
                'new_user': False,
                'user_details': {
                    'name': usr['name'],
                    'use_count': usr['use_count'],
                    'since': datetime.datetime.strptime(usr['since'], '%Y-%m-%d-%H-%M-%S')
                },
                'last_school_code': usr['last_school_code']
            }, g_config)

        else:
            return None
Пример #30
0
def login():
    if current_user.is_authenticated:
        flash('You are already logged in.', 'info')
        return redirect(url_for('admin'))

    form = LoginForm()
    if form.validate_on_submit():
        try:
            user = User.load(form.username.data)

            if not user.authenticate(form.password.data):
                raise ValueError('Invalid password.')

            login_user(user)
            flash('Successfully logged in.', 'success')
            log(user.get_id(), request.remote_addr, 'login', '')

            next_addr = request.args.get('next')
            if not is_safe_url(next_addr, {request.host, }):
                return redirect(url_for('admin'))

            return redirect(next_addr or url_for('admin'))
        except (NameError, ValueError):
            flash('Invalid username or password.', 'danger')
            return redirect(url_for('login'))
    return render_template('login.html', title='Sign in', form=form)
Пример #31
0
 def test_init_user_with_correct_info(self):
   username = "******"
   phones = "13800000000"
   user = User(username,phones)
   self.assertEqual(user.username, username)
   self.assertEqual(user.phones,[phones])
   self.assertEqual("<Username:{0},Phone:{1}>".format(username,phones),str(user))
Пример #32
0
def signup():
    form1 = SignupForm()
    form2 = LoginForm()
    if form1.validate_on_submit():
        if User.is_email_taken(form1.email.data):
            return render_template('user/index.html', form1=form1,form2=form2, error = 'Email Address Already Taken!' )
        user = User()
        user.dob = request.form.get('date')
        if user.dob:
            form1.populate_obj(user)
            db.session.add(user)
            db.session.commit()
            login_user(user)
            return redirect(url_for('user.userprofile',firstname=user.firstname))
        return render_template('user/index.html', form1=form1, form2=form2, error='error')
    return render_template('user/index.html', form1=form1, form2=form2)
Пример #33
0
def process_login():
    next_url = request.args.get('next')
    form = LoginForm()
    if form.validate_on_submit():
        user_json = admin_api_client.authenticate_user(form.email_address.data, form.password.data)
        if user_json:
            user = User.from_json(user_json)
            login_user(user)
            session['organisation_name'] = "GDS Notify"
            if next_url and next_url.startswith('/admin'):
                return redirect(next_url)

            return redirect(url_for('.view_dashboard'))
        else:
            flash("no_account", "error")
            return render_template(
                "login.html",
                form=form,
                **get_template_data()), 403

    else:
        return render_template(
            'login.html',
            **get_template_data(form=form)
        ), 400
Пример #34
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        username = request.form["username"]
        email = request.form["email"]
        password = request.form["password"]

        check_user = User.query.filter_by(username=username).first()
        check_email = User.query.filter_by(email=email).first()
        if check_user:
            flash('This username already exist!', 'danger')
            return redirect(url_for('register'))
        elif check_email:
            flash('This email already exist!', 'danger')
            return redirect(url_for('register'))
        new_user = User(username=username,
                        email=email,
                        password=generate_password_hash(password, "sha256"))
        db.session.add(new_user)
        db.session.commit()
        flash('Registration successful!', 'success')
        return redirect(url_for('home'))
    return render_template('register.html', title="Sign Up", form=form)
Пример #35
0
    def post(self, request):
        if len(request.POST['password']) <= 8:
            return HttpResponseBadRequest('Password is not valid')
        if "_" not in request.POST['password']:
            return HttpResponseBadRequest('Password is not valid')
        if UserFrameworkRepository.get_instance().find_by_email(
                request.POST['email']) is not None:
            return HttpResponseBadRequest('The email is already in use')
        user = User(randint(1, 999999), request.POST['name'],
                    request.POST['email'])
        UserFrameworkRepository.get_instance().save(user)

        # Send a confirmation email
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL("smtp.gmail.com", 465,
                              context=context) as server:
            # Uncomment this lines with a valid username and password
            # server.login("*****@*****.**", "myPassword")
            # server.sendmail('*****@*****.**', request.POST['email'], 'Confirmation link')
            pass

        return JsonResponse({
            'name': user.name,
            'email': user.email,
            'id': user.id
        })
Пример #36
0
def guest():
    session.clear()
    db = get_db()
    guest = db.execute(
        'SELECT * FROM Panelists WHERE panelist_id = 2').fetchone()
    login_user(User(guest))
    return redirect(url_for('views.home'))
Пример #37
0
def registration():
    if request.method == 'GET':
        return render_template('auth/registration.html', title='Registration',
                               form=RegistrationForm())

    form = RegistrationForm()
    username = form.username.data
    full_name = form.full_name.data
    email = form.email.data
    password = form.password.data

    if form.validate_on_submit():
        try:
            mongo.db.users.insert({'_id': username,
                                   'full_name': full_name,
                                   'email': email,
                                   'password': User.generate_hash(password),
                                   'registered_in': datetime.datetime.utcnow()
                                   })

            flash('Successfully created an account!', category='success')
            send_email(email, full_name, username, password)
            return redirect(url_for("auth.login"))
        except DuplicateKeyError:
            flash('Username already exist', category='error')
    return render_template('auth/registration.html', form=form)
Пример #38
0
def signup():

    email = request.form["email"]
    uname = request.form["name"]
    password = request.form["password"]
    repeat = request.form["repeat"]

    result = None
    json_response = {}

    try:
        if email and uname and password and repeat:

            email = email.lower()
            uname = uname.strip()

            user = User()
            user.name = uname
            user.email = email
            user.password = password

            user_mapper = UserDAO()
            user_id = user_mapper.add(user)
            print user_id, "new user"

        else:
            json_respons['error'] = True
            json_response['data'] = "params error"

    except Exception as e:
        print "error while signing up user"
        print e
        
        # 500 internal server error
        raise ExceptionResponse()

    if user_id:
        json_response['error'] = False
        json_response['data'] = "Success!"
    else:
        json_response['error'] = True
        json_response['data'] = "Error signing up user"

    return jsonify(json_response)
Пример #39
0
def login():
    form1 = SignupForm()
    form2 = LoginForm()
    if form2.validate_on_submit():
        user , authenticated = User.authenticate(form2.useremail.data,form2.password.data)
        if not authenticated:
            return render_template('user/index.html',form1=form1, form2=form2,usererror='Invalid email or password.')
        login_user(user, form2.remember_me.data)
        return redirect(url_for('user.userprofile',firstname=user.firstname))
    return render_template('user/index.html',form1=form1, form2=form2)
Пример #40
0
def reset_password():
    token = request.args.get('token',None)
    verifed_result = User.verify_token(token)
    if token and verifed_result:
        form = ResetPasswordForm()
        if form.validate_on_submit():
            password = form.password.data
            verifed_result.password = password
            db.session.add(verifed_result)
            db.session.commit()
            return redirect('user.login')
        return render_template('user/reset_password.html',form=form)
    return "Token expired"
Пример #41
0
def login():
    if request.method == 'GET':
        return render_template('auth/login.html', title='Log In', form=LoginForm())

    form = LoginForm()
    username = form.username.data
    password = form.password.data
    if form.validate_on_submit():
        user = mongo.db.users.find_one({'_id': username})
        if user and User.verify_password(user['password'], password):
            user_obj = User(user['_id'])
            login_user(user_obj)
            return redirect(request.args.get("next") or url_for("main.home"))
        flash("Wrong username or password.", category='error')
    return render_template('auth/login.html', title='Log In', form=form)
Пример #42
0
from flask import render_template, redirect, session, url_for, request
from datetime import datetime, date, timedelta
from app import app, db
from app.model import slack_user, message_channel, message
from app.channel import Channel
from app.user import User
from app.message_class import Message_Class
from flask.ext.sqlalchemy import SQLAlchemy
from wtforms import SelectMultipleField, SubmitField, DateField, SelectField
from sqlalchemy import desc
from flask_wtf import Form
from wtforms import DateField
import time

#GLOBAL VARIABLES
usr = User()
ch = Channel()
#Querying the database for all exsisting users and chanels, 
#then returning them as an ordered dictionary
allUserData = usr.userList()
allChannelData = ch.channelList()

#Formating dictionaries into a list of tuples for dropdown fields
def formatDataForDropdown(dataDictionary):
    avaliableSelections = [('None', 'All')]
    for key in dataDictionary:
        selection = (key, key)
        avaliableSelections.append(selection)
    return avaliableSelections

Пример #43
0
 def delete_test_user(self, username):
     """  deletes the user from database """
     user = User(username, 'dummy')
     user.delete_user()
Пример #44
0
def load_user(user_id):
    return User.load_user(admin_api_client, user_id)