Esempio n. 1
0
async def handler(websocket, path):
    async for message in websocket:
        if json.loads(message).get('request') == "register":
            print(json.loads(message))
            await websocket.send("ok")
            creds = await websocket.recv()
            print(creds)
            if not utils.validate_user(creds):
                await websocket.send("error")
            creds = json.loads(creds)
            if search_user(creds['usr']):
                await websocket.send("error")
            else:
                append_user(creds['usr'], creds['pwd'])
                await websocket.send("success")

        elif json.loads(message).get('request') == 'login':
            print(json.loads(message))
            await websocket.send("ok")
            creds = await websocket.recv()
            print(creds)
            if not utils.validate_user(creds):
                await websocket.send("error")
            creds = json.loads(creds)
            if login_user(creds['usr'], creds['pwd']):
                await websocket.send("success")
            else:
                await websocket.send("error")

        await websocket.send("Server response: Login attempt from {}".format(
            websocket.local_address))
Esempio n. 2
0
def edit(id):
    validate_user(id)

    # store info
    store_query = str(
        db.execute(
            f"SELECT s.id AS store_id, s.name, s.address_id AS address, s.front_pic, a.* FROM stores AS s INNER JOIN addresses AS a ON s.address_id = a.id INNER JOIN business AS b ON s.business_id = b.id WHERE s.id = :store AND b.user_id = :user",
            store=int(id),
            user=session['user_id']))
    store = ast.literal_eval(store_query[1:len(store_query) - 1])

    action = request.path[request.path.rfind("/") + 1:]

    if request.method == POST:
        form = StoreForm()

        if form.validate():
            print(form.picture.data.filename)

            if request.files["picture"]:
                image = request.files["picture"]
                print(image)
                #create the new image name
                extension = image.filename.split('.')[1]
                image_name = "store_front_pic_" + id + "." + extension
                #save the new image and insert it in the DB
                image.save(
                    os.path.join(app.config["IMAGE_UPLOADS"], image_name))
                db.execute(
                    "UPDATE stores SET front_pic=:front_pic WHERE id=:id",
                    front_pic=image_name,
                    id=id)
                Picture('', image_name, '').create_thumbnail()

            # update store name
            db.execute("UPDATE stores SET name = :name WHERE id = :store",
                       name=form.name.data,
                       store=store["store_id"])

            # update store address
            db.execute(
                f"UPDATE addresses SET street = :street, number = :number, zip_code = :zipcode, city = :city, region = :region, country = :country WHERE id = :id",
                id=store["address"],
                street=form.street.data,
                number=form.number.data,
                zipcode=form.zip_code.data,
                city=form.city.data,
                region=form.region.data,
                country=form.country.data)
        else:
            return render_template(MANAGE_STORE_PAGE, form=form, store=store)
        return redirect(url_for(STORE, id=id))
    return render_template(MANAGE_STORE_PAGE,
                           store=store,
                           form=StoreForm(formdata=MultiDict(store)),
                           action=action)
Esempio n. 3
0
def login():
    '''
    Handle user logins.
    '''
    now = datetime.now()
    launch = datetime(2016, 3, 28, 19, 30, 0)
    begin = now >= launch
    print(launch, now)
    if begin is False:
        return redirect('/')

    if request.method == "POST":
        username = request.form.get('username').strip()
        password = request.form.get('password').strip()

        if validate_user(database, username, password):
            auth_user = User(username)
            login_user(auth_user)
            user_level = get_level(database, current_user.id)
            return redirect(get_url(database, user_level))

        else:
            return render_template('login.html', force=False, error=True)
    else:
        if current_user.is_authenticated:
            user_level = get_level(database, current_user.id)
            resume = get_url(database, user_level)
            return render_template('login.html',
                                   force=True,
                                   username=current_user.id,
                                   error=False,
                                   resume=resume)

        return render_template('login.html', force=False, error=None)
Esempio n. 4
0
def login():
    '''
    Handle user logins.
    '''
    now = datetime.now()
    launch = datetime(2016, 3, 28, 19, 30, 0)
    begin = now >= launch
    print(launch, now)
    if begin is False:
        return redirect('/')

    if request.method == "POST":
        username = request.form.get('username').strip()
        password = request.form.get('password').strip()

        if validate_user(database, username, password):
            auth_user = User(username)
            login_user(auth_user)
            user_level = get_level(database, current_user.id)
            return redirect(get_url(database, user_level))

        else:
            return render_template('login.html', force=False, error=True)
    else:
        if current_user.is_authenticated:
            user_level = get_level(database, current_user.id)
            resume = get_url(database, user_level)
            return render_template('login.html', force=True,
                                   username=current_user.id, error=False,
                                   resume=resume)

        return render_template('login.html', force=False, error=None)
async def register():
    username = input("Username:"******"Password:"******"\nCould not verify if the password is compromised.\n")
    else:
        print("\nPassword is compromised. Must use another password.\n")
        raise Exception("Compromised password at registration phase.")
    rpassword = getpass.getpass("Repeat password:"******"\nPasswords are not the same.\n")
        raise Exception("Passwords differ at registration phase.")
    password = utils.hash(password)
    creds = utils.create_json(usr=username, pwd=password)
    if utils.validate_user(creds):
        async with websockets.connect(uri) as websocket:
            await websocket.send(utils.create_json(request="register"))
            resp = await websocket.recv()
            if resp == "ok":
                await websocket.send(creds)
                resp = await websocket.recv()
                if resp == "success":
                    print("registration successful")
                else:
                    raise Exception('\nServer could not register the user.')
            else:
                raise Exception('\nServer could not register the user.')
Esempio n. 6
0
def login():
    reason = 'Unknown error.'
    redir = request.args.get('next')

    if redir is None:
        redir = ''
    else:
        redir = '?next={}'.format(redir)

    if not event_start(EVENT_DATA):
        if ENV_DEV:
            pass
        else:
            return redirect('/')

    if request.method == "POST":
        try:
            uname = request.form.get('uname').strip()
            pword = request.form.get('pword').strip()

            if validate_user(get_db().cursor(), uname, pword):
                auth_user = User(uname)
                login_user(auth_user)

                if request.args.get('next') is None:
                    if current_user.is_authenticated:
                        return redirect(
                            routing(
                                EVENT_DATA,
                                get_user_level(get_db().cursor(),
                                               current_user.id), 'path'))

                if is_safe_url(request, request.args.get('next')):
                    return redirect(request.args.get('next'))
                else:
                    abort(400)
            else:
                reason = 'Incorrect username or password.'
                raise GameException
        except GameException:
            return render_template(
                'login.html',
                event="NETWORK TREASURE HUNT",
                social="https://www.instagram.com/acespvg/?hl=en",
                host="ACESPVG",
                error=True,
                reason=reason,
                year=YEAR,
                next=redir)
    else:
        return render_template(
            'login.html',
            event="NETWORK TREASURE HUNT",
            social="https://www.instagram.com/acespvg/?hl=en",
            host="ACESPVG",
            error=False,
            reason='',
            next=redir,
            year=YEAR)
Esempio n. 7
0
def store(id):
    validate_user(id)

    # store info
    store_query = str(
        db.execute(
            f"SELECT s.id AS store_id, s.name, s.front_pic, a.* FROM stores AS s INNER JOIN addresses AS a ON s.address_id = a.id INNER JOIN business AS b ON s.business_id = b.id WHERE s.id = :store AND b.user_id = :user",
            store=int(id),
            user=session['user_id']))
    store = ast.literal_eval(store_query[1:len(store_query) - 1])

    # products info
    products = db.execute(
        f"SELECT p.* FROM products AS p INNER JOIN business AS b ON p.business_id = b.id INNER JOIN stores AS s ON b.id = s.business_id WHERE s.id = :store AND b.user_id = :user",
        store=int(id),
        user=session['user_id'])

    return render_template(STORE_PAGE, store=store, products=products)
def login_user():
    user_email = request.json["email"]
    user_password = request.json["password"]

    user_token = validate_user(user_email, user_password)

    if user_token:
        return jsonify({"jwt_token": user_token})
    else:
        Response(status=401)
Esempio n. 9
0
def login_submit():
   form = LoginForm(request.form)
   if form.validate() and utils.validate_user(form.username.data, form.password.data):
      # Log the user in.
      session['uid'] = form.username.data

      return render_template('login_redirect.html')
   else:
      flash("Incorrect username and/or password.")
      return redirect("/login/")
Esempio n. 10
0
def login_user():
    print(request.json)
    user_email = request.json["email"]
    user_password = request.json["password"]

    user_token = validate_user(user_email, user_password)

    if user_token:
        print(user_token)
        return jsonify({
            "jwt_token": user_token,
            "message": "Successfully logged in: " + user_email
        })
Esempio n. 11
0
async def on_message(ctx):
    user = ctx.message.author

    # Send acknowledgement to user on current channel
    current_channel = ctx.message.channel
    await current_channel.send(
        f'<@{user.id}> we have started registration for you, '
        'keep an eye on your DMs for further instructions. :wink:'
    )

    user_dm = await user.create_dm()
    user_roles = [role.name for role in user.roles]

    # Check whether the user has already registered
    user_exists, userHash = utils.validate_user(user.id)
    if user_exists:
        await current_channel.send(
            f'We have met before <@{user.id}>! I have sent you a present on DM :smiling_imp:'
        )
        await user_dm.send(
            f'There you go with you hashCode: `{userHash}`. '
            'You can now register yourself through the CLI.'
            f'When in doubt, head over to our documentation: {config.DOCUMENTATION_URL}'
        )
        return

    # Send greetings to user on DM
    await user_dm.send(config.LOADING_GIF_URL)
    await user_dm.send(
        f'<@{user.id}> we have started moving things for you! Meanwhile, you '
        'can have a look at our documentation: '
    )

    # Register user on Kaal Backend
    status_code, userHash = utils.registerUser(user.id, user.name, user_roles)

    if userHash:
        await user_dm.send(config.BOOM_GIF_URL)
        await user_dm.send(
            f'Kudos <@{user.id}>! There you go with you hashCode: `{userHash}`. '
            'You can now register yourself through the CLI.'
            'When in doubt, head over to our documentation: '
        )
    else:
        await user_dm.send(
            'Oh no! It seems like we are currently facing a problem registering '
            'you in our database, please report your bug report on our GitHub, '
            f'with this code `{status_code}`. Our developers will help you!'
        )

    await create_webhooks_for_users(ctx, user, userHash)
Esempio n. 12
0
def home(request):
    eat_ratings = utils.get_eat_options(10)
    play_ratings = utils.get_play_options(10)
    text_form = forms.TextInputForm(request.POST or None)
    context = {
        'form': text_form,
        'eat_ratings': eat_ratings,
        'play_ratings': play_ratings,
    }

    if request.method == 'POST':
        if utils.validate_user(request.POST['twitter']) or request.POST['textInput'] is not "":
            eat_data = []
            play_data = []
            for eat_rating in utils.get_all_eat_options():
                eat_element = dict()
                eat_element['activity'] = eat_rating
                request_label = eat_rating + '_eat'
                rating = request.POST.get(request_label, False)
                if not rating:
                    pass
                else:
                    eat_element['rating'] = int(rating)
                    eat_data.append(eat_element)
            for play_rating in utils.get_all_play_options():
                play_element = dict()
                play_element['activity'] = play_rating
                request_label = play_rating + '_play'
                rating = request.POST.get(request_label, False)
                if not rating:
                    pass
                else:
                    play_element['rating'] = int(rating)
                    play_data.append(play_element)
            if request.POST['textInput'] != '':
                text = re.sub(r'[^\x00-\x7F]+', ' ', request.POST.get('textInput', False))
                # Remove non-ASCII
                personality_json = json.dumps(personality_analyzer.run_text(text))
            else:
                personality_json = json.dumps(personality_analyzer.run_twitter(request.POST.get('twitter', False)))
            eat_json = json.dumps(eat_data)
            play_json = json.dumps(play_data)
            commit_to_sql.add_record(personality_json, eat_json, play_json)
            return HttpResponseRedirect(reverse('survey:finished'))
        else:
            return render(request, "home.html", context)

    return render(request, "home.html", context)
Esempio n. 13
0
def login():
    print(session)
    if request.method == 'POST':
        form_data = request.form
        validated_user = validate_user(form_data)

        if not validated_user:
            flash(f'Wrong credentials!', 'danger')
            return redirect('/login')

        session['username'] = form_data.get('username')
        return redirect('/')

    return render_template('_login.html')

    return render_template('_login.html')
Esempio n. 14
0
def changepassword_submit():
   form = ChangePasswordForm(request.form)
   if form.validate():
      if utils.validate_user(session['uid'], form.oldpassword.data):
         # Change their password. 
         if utils.change_password(session['uid'], form.oldpassword.data, form.newpassword.data):
            flash("Password changed!")
         else:
            session.clear()
            flash("No LDAP client object?")
      else:
         flash("Old password incorrect.")
      return redirect("/")
   else:
      flash("Password change failed. Please fill in all fields and make sure you type the new password correctly both times.")
      return redirect("/changepassword/")
async def login():
    username = input("Username:"******"Password:"******"login"))
            resp = await websocket.recv()
            if resp == "ok":
                await websocket.send(creds)
                resp = await websocket.recv()
                if resp == "success":
                    print("login successful")
                else:
                    raise Exception('\nUser could not log in.')
            else:
                raise Exception('\nUser could not log in.')
Esempio n. 16
0
 def post(self):
     userid = self.request.cookies.get("userid")
     if userid:
         userid = utils.verify_cookie(userid)
         if userid:
             user = utils.validate_user(userid)
             if user:
                 act_name = self.request.get("activity_name")
                 new_act = models.ActivityModel(userid=userid, name=activity_name, when=datetime.datetime.now())
                 new_act.put()
                 user.last_seen = datetime.datetime.now()
                 user.put()
                 self.redirect("/panel")
             else:
                 self.redirect("login")
         else:
             self.redirect("login")
     else:
         self.redirect("login")
Esempio n. 17
0
def login():
    reason = 'Unknown error.'
    redir = request.args.get('next')

    if redir is None:
        redir = ''
    else:
        redir = '?next={}'.format(redir)

    if not event_start(EVENT_DATA):
        if ENV_DEV:
            pass
        else:
            return redirect('/')

    if request.method == "POST":
        try:
            uname = request.form.get('uname').strip()
            pword = request.form.get('pword').strip()

            if validate_user(get_db().cursor(), uname, pword):
                auth_user = User(uname)
                login_user(auth_user)

                if request.args.get('next') is None:
                    if current_user.is_authenticated:
                        return redirect(
                            routing(
                                EVENT_DATA,
                                get_user_level(get_db().cursor(),
                                               current_user.id), 'path'))

                if is_safe_url(request, request.args.get('next')):
                    return redirect(request.args.get('next'))
                else:
                    abort(400)
            else:
                reason = 'Incorrect username or password.'
                raise GameException
        except GameException:
            return render_template('login.html',
                                   event=EVENT_DATA['name'],
                                   host=EVENT_DATA['host'],
                                   faq=EVENT_DATA['faq'],
                                   discuss=EVENT_DATA['discuss'],
                                   social=EVENT_DATA['social'],
                                   error=True,
                                   reason=reason,
                                   year=YEAR,
                                   next=redir)
    else:
        return render_template('login.html',
                               event=EVENT_DATA['name'],
                               host=EVENT_DATA['host'],
                               faq=EVENT_DATA['faq'],
                               social=EVENT_DATA['social'],
                               discuss=EVENT_DATA['discuss'],
                               error=False,
                               reason='',
                               next=redir,
                               year=YEAR)