Example #1
0
 def after_show(self, context, data_dict):
     # system processes should have access to all resources
     if context.get('ignore_auth', False) is not True:
         resource_visibility_helpers.process_resources(
             data_dict, helpers.get_user())
         de_identified_data_helpers.process_de_identified_data_dict(
             data_dict, helpers.get_user())
     resource_freshness_helpers.process_next_update_due(data_dict)
Example #2
0
 def after_search(self, search_results, search_params):
     for data_dict in search_results.get('results', []):
         resource_visibility_helpers.process_resources(
             data_dict, helpers.get_user())
         de_identified_data_helpers.process_de_identified_data_dict(
             data_dict, helpers.get_user())
         resource_freshness_helpers.process_next_update_due(data_dict)
     return search_results
Example #3
0
def all():
    db = mysql.connection.cursor()

    user = get_user(db, session['user_id'])
    userid = session['user_id']

    try:
        # Select all from 'store' table and 'categories' table where userid is current userid
        db.execute("SELECT item, itemid, location, comments, userid, store.catid, category FROM store INNER JOIN categories on categories.catid=store.catid WHERE userid=%(userid)s", \
            {'userid': userid} )

        all_cat_data = db_extract(db)

        # sort a list of dictionaries by key name
        all_cat_data.sort(key=operator.itemgetter('catid'))

        return render_template('all.html',
                               userData=all_cat_data,
                               category=False,
                               page="Browse all",
                               user=user,
                               side='sidebar')

    except Exception as e:
        print(e)
        return render_template('index.html',
                               category=False,
                               page="Add your stuff")
Example #4
0
def edit(item_id):
    db = mysql.connection.cursor()

    # if function returns None, value contains characters other than digits (manually entered in address bar)
    if item_query(item_id, db) is None:
        return internal_error(404)

    try:
        user = get_user(db, session['user_id'])
        user_id = session['user_id']

        # Make sql query of item, and retrieve all data in its row
        item_data = item_query(item_id, db)

        # Does current user own selected entry (itemid)?
        if user_id == item_data[0]['userid'] and int(
                item_id) == item_data[0]['itemid']:
            # Return edit page with fields completed with previously entered info
            return render_template('/edit.html',
                                   user=user,
                                   userData=item_data,
                                   side='sidebar',
                                   category=False,
                                   page="Edit")
        else:
            return sorry(
                message='There was an error matching this item to your account.'
            )

    # If any erros, render index page
    except Exception as e:
        print(e)
        return sorry(
            message='There was an error matching this item to your account.')
Example #5
0
def user_has_datarequest_admin_access(datarequest_id, include_editor_access,
                                      context):
    user = helpers.get_user()
    # If user is 'None' - they are not logged in.
    if user is None:
        return False
    if user.sysadmin:
        return True

    groups_admin = user.get_groups('organization', 'admin')
    groups_editor = user.get_groups('organization',
                                    'editor') if include_editor_access else []
    groups_list = groups_admin + groups_editor
    organisation_list = [g for g in groups_list if g.type == 'organization']
    user_has_access = len(organisation_list) > 0
    # New Data Request. Check if user has any admin/editor access
    if not datarequest_id or len(datarequest_id) == 0:
        return user_has_access
    # User has admin/editor access so check if they are a member of the default_organisation_id or datarequest_organisation_id
    elif user_has_access:
        default_organisation_id = helpers.datarequest_default_organisation_id()
        datarequest_organisation_id = toolkit.get_action(
            constants.SHOW_DATAREQUEST)(context, {
                'id': datarequest_id
            }).get('organization_id')
        for organisation in organisation_list:
            print('organisation.id: s%', organisation.id)
            # Is user an admin/editor of the default organisation
            if organisation.id == default_organisation_id:
                return True
            # Is user an admin/editor of the data request selected organisation
            elif organisation.id == datarequest_organisation_id:
                return True

    return False
Example #6
0
  def see_token():
    page = 0
    length = 20
    r = get_request()

    if r.args.get('page') is not None:
      try:
        choosen_page = int(r.args.get('page'))

        if choosen_page >= 0:
          page = choosen_page
      except:
        return ERRORS.BAD_REQUEST

    if r.args.get('count') is not None:
      try:
        choosen_count = int(r.args.get('count'))

        if 0 < choosen_count <= 100:
          length = choosen_count
      except:
        return ERRORS.BAD_REQUEST

    start = page * length
    end = (page + 1) * length

    # Teachers are allowed to see tokens of all users (may be heavy)
    if is_teacher():
      return flask.jsonify(Token.query.all()[start:end])

    # Send all tokens of logged user
    id_etu = get_user().id_etu
    return flask.jsonify(Token.query.filter_by(id_etu=id_etu).all()[start:end])
Example #7
0
def _get_context():
    return {
        'model': model,
        'session': model.Session,
        'user': g.user,
        'auth_user_obj': helpers.get_user()
    }
def test_get_current():
    email = get_random_email()
    create_user(email, 'pass')
    token = login_user(email, 'pass')
    user = get_user(token=token)
    assert user['email'] == email
    assert user['balance'] == 2.5
def login():
    '''
        Log out view, redirecting to the RSS list page.
    '''
    if not session.get('logged_in'):

        form = LoginForm(request.form)
        if request.method == 'POST':

            name = request.form['username'].lower()
            password = request.form['password']

            if form.validate():
                if credentials_valid(name, password):

                    session['logged_in'] = True
                    session['name'] = name
                    return json.dumps({'status': 'Login successful'})

                else:
                    return json.dumps({'status': 'Invalid user/pass'})

            else:
                return json.dumps({'status': 'All fields required'})

        elif request.method == 'GET':
            return render_template('index.html', form=form)

    # Once user is auth-ed, opens RSS feed for stations.
    return render_template('home.html',
                           stations_list=get_stations_list(),
                           user=get_user())
Example #10
0
def index():
    """Redirect to user's homepage"""

    # Get user's id
    user = get_user(session["user_id"])

    # Render template with my_prof set to True because user is accessing own profile
    return render_template("index.html", user=user, my_prof=True)
Example #11
0
def add_fee(group, amount, payer_id, participants, date=None):
    fee = Fee(amount = amount,
              payer = get_user(payer_id),
              participants = participants,
              group = group,)
    if date:
        fee.date = date
    fee.put()
    return fee
Example #12
0
def main_menu(inventory):
    """
    Main menu for the auction program. User can choose roles, edit existing
    bidders, or quit.
    """
    while True:

        print()
        print("[A]dmin page.")
        print("[B]idder page.")
        print("[N]ew bidder.")
        print("[D]elete bidder.")
        print("[Q]uit.")

        choice = input(">> ").lower()

        if choice.startswith("a"):
            user = get_user(inventory)

            if isinstance(user, Admin):
                admin_menu(inventory, user)
            else:
                print("Not an admin!")

        elif choice.startswith("b"):
            bidder = get_user(inventory)
            bidder_menu(inventory, bidder)

        elif choice.startswith("n"):
            username, password = login()
            bidder = inventory.add_bidder(username, password)

            bidder_menu(inventory, bidder)

        elif choice.startswith("d"):
            bidder = get_user(inventory)
            inventory.delete_bidder(bidder)
            print("Bidder deleted!")

        elif choice.startswith("q"):
            break

        else:
            print("Invalid input!")
Example #13
0
 def GET(self, wf=None):
     u = helpers.get_user()
     uemail = u and u.email
     if not wf:
 	    #create a new form and initialize with current user details
         wf = forms.wyrform()
 	    u and fill_user_details(wf, u)
 	captcha_html = prepare_for_captcha(wf)
 	msg, msg_type = helpers.get_delete_msg()
 	return render.writerep(wf, useremail=uemail, captchas=captcha_html, msg=msg)
Example #14
0
def add():
    db = mysql.connection.cursor()

    user = get_user(db, session['user_id'])

    if request.method == 'POST':
        category = request.form.get('category')
        item = request.form.get('item')
        location = request.form.get('location')
        comments = request.form.get('comments')

        #===================
        # Backend validate form / check for errors
        error0 = "Please enter a category."
        error1 = "Please enter an item."
        error2 = "Please enter a location."

        if category == None:
            return render_template('add.html', error0=error0)

        if item == "":
            return render_template('add.html', error1=error1)

        if location == "":
            return render_template('add.html', error2=error2)

        cat_id = get_cat_id(category, db)

        db.execute("INSERT INTO store (item, location, comments, catid, userid) \
         VALUES (%(item)s, %(location)s, %(comments)s, %(catid)s, %(userid)s)"                                                                              , \
          {'item': item, 'location': location, 'comments': comments, 'catid': cat_id, 'userid': session['user_id']})

        mysql.connection.commit()

        # Select all user's 'store' data from current category that user is adding to
        db.execute("SELECT * FROM store WHERE userid=%(userid)s AND catid=%(catid)s", \
            {'userid': session['user_id'], 'catid': cat_id})
        user_cat_data = db_extract(db)

        thelength = len(user_cat_data)

        return render_template('category.html',
                               user=user,
                               userData=user_cat_data,
                               category=category,
                               listlength=thelength,
                               side='sidebar')

    else:
        return render_template('add.html',
                               user=user,
                               side='sidebar',
                               category=False,
                               page="Add your stuff")
Example #15
0
    def get(self):
        # user check
        user = helpers.get_user(self)
        if not user.get('id'):
            tv = {"user": user}
            t = env.get_template('login.html')
            return self.response.out.write(t.render(T=tv))

        t = env.get_template('menu.html')
        tv = {"user": user}
        return self.response.out.write(t.render(T=tv))
Example #16
0
    def get(self):
        # user check
        user = helpers.get_user(self)
        if not user.get('id'):
            tv = {"user": user}
            t = env.get_template('login.html')
            return self.response.out.write(t.render(T=tv))

        t = env.get_template('menu.html')
        tv = {"user": user}
        return self.response.out.write(t.render(T=tv))
Example #17
0
def discussions():
    """Redirect to discussions page"""

    # Get current user
    user = get_user(session["user_id"])

    # Get posts from most to least recent
    posts = query_db("SELECT * FROM posts ORDER BY stamp DESC")

    # Redirect posts to about page
    return render_template("discussions.html", user=user, posts=posts)
Example #18
0
def store_user(credentials):
    user = get_user(credentials)
    flask.session['user'] = {
        'is_authenticated':
        True,
        'name':
        user['displayName'],
        'email':
        user['mail'] if
        (user['mail'] is not None) else user['userPrincipalName']
    }
Example #19
0
def settings():
    if session.get('logged_in'):
        if request.method == 'POST':
            password = request.form['password']
            if password != "":
                password = helpers.hash_password(password)
            email = request.form['email']
            helpers.change_user(password=password, email=email)
            return json.dumps({'status': 'Saved'})
        user = helpers.get_user()
        return render_template('settings.html', user=user)
    return redirect(url_for('login'))
Example #20
0
def sorry(message):
    db = mysql.connection.cursor()

    if session['user_id']:
        user = get_user(db, session['user_id'])
        return render_template('sorry.html',
                               user=user,
                               category=False,
                               page="Error",
                               message=message)
    else:
        return render_template('login.html')
Example #21
0
def server_error(error):
    db = mysql.connection.cursor()

    if session['user_id']:
        user = get_user(db, session['user_id'])
        return render_template('sorry.html',
                               user=user,
                               category=False,
                               page="Error",
                               message="Sorry, there was an error on our end.")
    else:
        return redirect('/login')
Example #22
0
def upload():
    if session.get('logged_in'):
        if request.method == 'POST':
            with open('temp.txt', 'r') as f:
                to = f.readline()
            user = helpers.get_user()
            for f in request.files.getlist('file'):
                f.save(
                    os.path.join(
                        app.config['UPLOADED_PATH'],
                        str(datetime.datetime.now()) + ' from: ' +
                        str(user.username) + ' to: ' + str(to)))
        return render_template('upload.html')
    return redirect(url_for('login'))
Example #23
0
    async def _balance_top(self, ctx, *args):
        print("Received command BALANCE TOP from", ctx.message.author)

        balances = sql_db.select_entry_sorted(helpers.conn, ctx.guild.id)

        embed = discord.Embed(title="Top 10 Balances",
                              color=helpers.bot_color(ctx))

        for bal in balances[0:max(10, len(balances))]:
            if (len(args) > 0 and bal[2] >= float(args[0])) or len(args) == 0:
                embed.add_field(name=helpers.get_user(bal[0]),
                                value="${:.2f}".format(bal[2]),
                                inline=False)

        await ctx.send(embed=embed)
Example #24
0
def internal_error(error):
    db = mysql.connection.cursor()

    if session.get('user_id'):
        if session['user_id']:
            user = get_user(db, session['user_id'])
            return render_template('sorry.html',
                                   user=user,
                                   category=False,
                                   page="Error",
                                   message="Sorry, this page does not exist.")
        else:
            return render_template('login.html')
    else:
        return render_template('login.html')
Example #25
0
 def authenticate(self, environ, identity):
     """Return username or None.
     """
     try:
         username = identity['login']
         password = identity['password']
     except KeyError:
         return None
    
      
     user = h.get_user(username)
     if user and encrypt(password) == user.password:
             return username
     else:
         return None
Example #26
0
def chat():
    """Redirect to public chat page"""

    # Get current user
    cur_user = get_user(session["user_id"])

    # Get most recent 10 public chat messages from database
    messages = query_db(
        "SELECT * FROM messages WHERE buddy=? ORDER BY stamp DESC LIMIT 10",
        [""])

    # Redirect to public chat page
    return render_template("chat.html",
                           user=cur_user,
                           dest="",
                           messages=messages)
Example #27
0
def login():
    if not session.get('logged_in'):
        form = LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = request.form['password']
            if form.validate():
                if helpers.credentials_valid(username, password):
                    session['logged_in'] = True
                    session['username'] = username
                    return json.dumps({'status': 'Login successful'})
                return json.dumps({'status': 'Invalid user/pass'})
            return json.dumps({'status': 'Both fields required'})
        return render_template('login.html', form=form)
    user = helpers.get_user()
    return render_template('home.html', user=user)
Example #28
0
def users():
    """Redirect to users page"""

    # Get all users
    users = query_db("SELECT * FROM users")

    # Get current user id
    user_id = session["user_id"]

    # Get current user information
    user = get_user(session["user_id"])

    # Redirect user to about page
    return render_template("users.html",
                           users=users,
                           curr_user=user_id,
                           user=user)
Example #29
0
    async def _balance(self, ctx, *args):
        if not helpers.check_channel(ctx): return
        print("Received command BALANCE from", ctx.message.author)
        await ctx.send("Command Received")
        bal = sql_db.select_entry(helpers.conn, ctx.author.id, ctx.guild.id)
        await ctx.send("Database got" + str(bal))

        embed = discord.Embed(title="Balance", color=helpers.bot_color(ctx))
        await ctx.send("Embed made")

        embed.add_field(name=helpers.get_user(bal[0]),
                        value="${:.2f}".format(bal[2]))
        await ctx.send("Field added")

        if bal != 0:
            await ctx.send(embed=embed)
        else:
            await ctx.send("Failed to get bal")
Example #30
0
def personal_user_info(xblock):
    """
    Provide additional standard LTI user personal information.
    """
    user = get_user(xblock)
    if not user:
        return

    user_full_name = user.profile.name
    names_list = user_full_name.split(' ', 1)

    params = {
        'lis_person_name_given': names_list[0],
    }

    if len(names_list) > 1:
        params['lis_person_name_family'] = names_list[1]

    return params
Example #31
0
def detail(request, group_id):
    group = get_group(group_id)
    if not group:
        raise Http404()
        
    require_privilege = check_user(group)
        
    summaries = [] +group.summaries
    summaries.sort()
    due_payer_index = group.summaries.index(summaries[0])
    due_payer = get_user(group.members[due_payer_index])

    params = {'fees': get_fees(group),
              'members': get_users(group),
              'is_valid_user': not require_privilege,
              'group': group,
              'due_payer': due_payer.name,
              'due_amount': -summaries[0], }

    return respond('group_detail.html', params)
Example #32
0
  def invalidate_token():
    r = get_request()
    token = r.headers.get('Authorization').replace('Bearer ', '', 1)

    if is_teacher():
      Token.query.filter_by(token=token).delete()
      db_session.commit()
      return ""
    else:
      current_etu_id = get_user().id_etu
      t: Token = Token.query.filter_by(token=token).one_or_none()

      if not t:
        return ERRORS.NOT_FOUND

      if t.id_etu == current_etu_id:
        db_session.delete(t)
        db_session.commit()
      else:
        return ERRORS.INVALID_CREDENTIALS
Example #33
0
def private(username):
    """Redirect to private chat page"""

    # Get current user
    cur_user = get_user(session["user_id"])

    # Get user current user wishes to chat with
    user = query_db("SELECT * FROM users WHERE id=?", [session["user_id"]],
                    one=True)

    # Get 10 most recent messages from conversation between these two users
    messages = query_db(
        "SELECT * FROM messages WHERE (username=? AND buddy=?) OR (username=? AND buddy=?) ORDER BY stamp DESC LIMIT 10",
        [user["username"], username, username, user["username"]])

    # Redirect to private chat page
    return render_template("chat.html",
                           user=cur_user,
                           dest=username,
                           messages=reversed(messages))
Example #34
0
def delete(request, group_id):
    try:
        group = get_group(group_id)
        require = check_user(group)
        if require:
            raise Exception("invalid user")
        if not request.GET.has_key('confirm'):
            params = {'name': group.name,
                      'confirm': "%s?confirm" % request.path,
                      'cancel': "/group/%s" % group_id,}
            return respond("confirm.html", params)
    except ValueError:
        return redirect('/redirect/?param')
    except:
        return redirect("/redirect/?%s" % require)
    else:
        for member_id in group.members:
           member = get_user(member_id)
           member.delete()
        group.delete()
        return home(request)
 def _user(self, username):
     tk.c.username = username
     user = User.get(username)
     tk.c.user_info = h.get_user(user.id)
     tk.c.sub_title = _('User Activities: %s'%(user.fullname or user.name) )
     tk.c.user_activity_list = h.list_activities_for_user(user_id=user.id)
Example #36
0
 def add_metadata(self, environ, identity):
     username = identity.get('repoze.who.userid')
     user = h.get_user(username)
     if user is not None:
         identity['user'] = user    
Example #37
0
 def get(self):
     t = env.get_template('front_top.html')
     tvars = {"user": helpers.get_user(self)}
     return self.response.out.write(t.render(T=tvars))
Example #38
0
def fill_user_details(form, user=None):
    user = user or helpers.get_user()
    if user:
        form.fill(userid=user.id)
        form.fill(user)
Example #39
0
def user_exists(username):
    return h.get_user(username) is not None  
Example #40
0
def executor(server, func, user):
    if helpers.is_local(server):
        if helpers.is_current_user(helpers.get_user(user)):
            return func
    stdin, input = helpers.r_popen2(server, "/usr/bin/env python", user=user)
    return functools.partial(executor_helper, stdin, input, func)