Ejemplo n.º 1
0
def info_printer(user):
    print 'Name:'
    print user.get_name()
    print 'Id:'
    print len(users) - 1
    print 'Status:'
    print user.get_status()
Ejemplo n.º 2
0
def index():
    if Access_token == "":
        req = urllib2.Request("https://api.clarifai.com/v1/token/")
        data = {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "grant_type": "client_credentials"}
        req.data = urllib.urlencode(data)
        u = urllib2.urlopen(req)
        response = u.read()
        data = json.loads(response)
        global Access_token
        Access_token = data["access_token"]
    paths = user.get_pics("all")
    images = []
    tags = []
    tagStrings = []
    count = 0
    for i in paths:
        images.append([])
        temp = i[0][13:]
        images[count].append(temp)
        count = count + 1
    for e in images:
        e.append(user.get_name("static/images"+e[0])[0][0])
        e.append(user.get_username(user.match_UID(e[1])))
        e.append(user.get_lat("static/images"+e[0])[0][0])
        e.append(user.get_lon("static/images"+e[0])[0][0])
    #get tags from database
    for i in range(len(images)):
        tags.append(user.get_tags(path+images[i][0]))
    for tag in tags:
        tagStrings.append(generateTags(tag[0]))
    if "username" not in session:
        return render_template("index.html", images=images, tagStrings=tagStrings)
    return render_template("index.html",username=session['username'], images=images, tagStrings=tagStrings)
Ejemplo n.º 3
0
def home():
    cookie_secret = request.cookies.get('user_secret')
    user_id = session.get_session(cookie_secret, db)
    if user_id is not None:
        email = user.get_email(user_id, db).strip()
        first_name = user.get_name(email, db)
        if first_name is not None:
            recipient_email = santa.get_recipient(email, db)
            recipient_name = user.get_name(recipient_email, db)
            recipient_last_name = user.get_last_name(recipient_email, db)
            if recipient_name is not None and recipient_last_name is not None:
                recipient_name = recipient_name + " " + recipient_last_name
                return render_template('show-santa.html', firstName=None, recipient_name=recipient_name)
            return render_template('show-santa.html', firstName=first_name, recipient_name=None)
        else:
            return redirect(flask.url_for('logout'))
    else:
        return render_template('login.html')
Ejemplo n.º 4
0
def login():
    if request.method == "GET":
        return render_template('login.html')  # prompt user to log in
    elif request.method == "POST":
        password = request.form['password']
        userid = request.form['userid']
        res = check_user_password(userid, password)
        if res == 1:  # correct password
            session['logged_in'] = True
            session['userid'] = userid
            session['user_name'] = get_name(userid)
            return redirect(url_for('index'))
        else:  # wrong password or wrong userid
            print(res)
            return render_template('login.html', res=res)
Ejemplo n.º 5
0
def ajax_create_new_user():
    email = request.args.get('email').strip()
    if user.get_name(email, db) is None:
        families = user.get_families(db)
        firstName = request.args.get('fName')
        lastName = request.args.get('lName')
        family = request.args.get('family')

        if not len(firstName) > 0 and len(lastName) > 0:
            return json.dumps({'success': False,
                               'outcome': '<p>Name appears to be invalid, please ensure to:</p><ul><li>Make sure to enter your first and last name</li></ul>'}), \
                   200, {
                       'ContentType': 'application/json'}
        if not validate_email(email):
            return json.dumps({'success': False,
                               'outcome': '<p>Email appears to be invalid, please ensure to:</p><ul><li>Enter a valid email address</li><li>The email account is active</li></ul>'}), \
                   200, {
                       'ContentType': 'application/json'}
        try:
            familyExists = False
            for familySingle in families:
                if int(family) is familySingle[0]:
                    familyExists = True
                    break
            if not familyExists:
                return json.dumps({'success': False,
                                   'outcome': '<p>Provided family was invalid, please ensure to:</p><ul><li>Select a family</li></ul>'}), 200, {
                           'ContentType': 'application/json'}
        except TypeError:
            return json.dumps({'success': False,
                               'outcome': '<p>Provided family was invalid, please ensure to:</p><ul><li>Select a family</li></ul>'}), 200, {
                       'ContentType': 'application/json'}

        if not user.create_user(firstName, lastName, email, family, db):
            return json.dumps({'success': False,
                               'outcome': '<p>Account creation failed. Please email [email protected] if this issue persists</p>'}), 500, {
                       'ContentType': 'application/json'}

        login_cookie = generate_session(email)
        return json.dumps({'success': True, 'outcome': '<p>Successfully created account</p>', 'redirect': '/',
                           'user_secret': login_cookie}), 200, {
                   'ContentType': 'application/json'}
    else:
        return json.dumps({'success': False, 'outcome': '<p>Account creation failed. Email already registered.</p>',
                           'redirect': '/'}), 200, {
                   'ContentType': 'application/json'}
Ejemplo n.º 6
0
def profile():
    if 'username' in session:
        paths = user.get_pics(user.get_UID(session['username']))
        images = []
        tags = []
        tagStrings = []
        count = 0
        for i in paths:
            images.append([])
            temp = i[0][13:]
            images[count].append(temp)
            count = count + 1
        for e in images:
            e.append(user.get_name("static/images"+e[0])[0][0])
            e.append(user.get_username(user.match_UID(e[1])))
        for i in range(len(images)):
            tags.append(user.get_tags(path+images[i][0]))
        for tag in tags:
            tagStrings.append(generateTags(tag[0]))
        return render_template("profile.html",images=images,username=session['username'],tagStrings=tagStrings)
    return redirect(url_for("login"))
Ejemplo n.º 7
0
def signup():
    if request.method == "GET":
        form = SignUpForm()
        return render_template('signup.html',
                               form=form)  # prompt user to sign up
    elif request.method == "POST":
        password = request.form['password']
        userid = request.form['userid']
        user_name = request.form['user_name']
        email = request.form['email']
        log_in = request.form.getlist('log_in')  # log me in too!
        if not get_name(userid):  # if user doesn't exist
            create_user(userid, user_name, password, email)
            if len(log_in) > 0:
                return redirect(
                    url_for('login'),
                    code=307)  # continue post request to log user in
            else:
                return redirect(url_for('login'))
        else:  # userid already taken
            form = SignUpForm()
            return render_template('signup.html', res=1, form=form)
Ejemplo n.º 8
0
    if user.signout(user_name):
        print("Successfully signed out.")
    else:
        second_option = input("Not signed in.\n1. Sign in?\n2. Exit?\n")  # Can't sign out if not signed in.
        if second_option == '1':
            sign_in(user_name)
        else:
            exit(0)


option = input('Please select an option below: \n1.Login.\n2.Register.\n')
if option == '1':
    username = input('Please enter your username: '******'Enter password: '******'Welcome ', user.get_name(username))
        print('Please choose an option below:')
        log = input('1. Sign-in.\n2. Signout.\n')
        if log == '1':
            sign_in(username)

        elif log == '2':
            sign_out(username)
        else:
            print('Incorrect selection.')  # Error handling

    else:
        print('Incorrect username and password combination.')
elif option == '2':
    print('Welcome to the registration page.')
    full_name = input('Please enter your full name: ')
Ejemplo n.º 9
0
async def execute_bot_command_line(bot, msg, chat_id, cmdline):

    cmd = cmdline
    args = ""

    if ' ' in cmdline:
        cmd, args = cmdline.split(" ", 1)

    sender_id = msg['from']['id']

    # Get user name of whoever sent the text

    sender_name = user.get_name(sender_id)

    # If the sender hasn't logged in, don't allow anything else but login

    if sender_name == None:

        if cmd == "login":

            username = await user.login(bot, args, chat_id, sender_id)

            first_name = None
            last_name = None
            name = "<Undefined>"

            try:
                first_name = msg['from']['first_name']
            except:
                pass

            try:
                name = msg['from']['last_name']
            except:
                pass

            if first_name != None and last_name == None:
                name = first_name
            elif first_name == None and last_name != None:
                name = last_name
            elif first_name != None and last_name != None:
                name = first_name + ' ' + last_name

            chat_info_str = ""
            if sender_id != chat_id:
                chat_info_str += "Sender ID " + str(sender_id) + ". "
            chat_info_str += "Chat ID " + str(
                chat_id) + ". Name [" + name + "]"

            if username != None:
                status = "Successful"
                # Tell me about the new login
                await bot.sendMessage(
                    secrets.MY_USER_ID,
                    "EVENT: Login of user " + username + ". " + chat_info_str)
            else:
                # Tell me about the failed login
                await utils.send_message(
                    bot, secrets.MY_USER_ID,
                    "EVENT: Failed login [" + args + "]. " + chat_info_str)

        else:
            await bot.sendMessage(
                chat_id, "Please, log in.\n" + "/login <username> <password>")

        return

    if cmd == "login":
        username = user.get_name(sender_id)
        await bot.sendMessage(chat_id,
                              "Already logged in as " + username + ".")
        return

    elif cmd == "logout":
        await user.logout(bot, args, chat_id, sender_id)
        return

    elif cmd == "help":
        plugins = "/" + "\n/".join(PLUGIN_LIST_NAMES)
        await bot.sendMessage(
            chat_id, "/login <username> <password>\n" + "/logout\n" +
            "/user\n" + "/plugin\n" + "/cmd\n" + plugins)
        return

    # Only continue if user has permission to do this, but don't tell the user
    # about the lack of permission.

    if not user.has_permission(sender_name, cmd):
        await bot.sendMessage(chat_id, "Command not available.")
        return

    # First, check all internal commands. Then, check plugins.

    if cmd == "user":

        if sender_id != secrets.MY_USER_ID:
            await bot.sendMessage(chat_id,
                                  "You have no permission to do that.")
            return

        if args.startswith("new "):
            await user.create(bot, args, chat_id)
            return

        elif args.startswith("remove "):
            await user.remove(bot, args, chat_id)
            return

        elif args.startswith("setpass "):
            await user.set_password(bot, args, chat_id)
            return

        elif args.startswith("addperm "):
            await user.add_permission(bot, args, chat_id)
            return

        elif args.startswith("removeperm "):
            await user.remove_permission(bot, args, chat_id)
            return

        elif args.startswith("listperm "):
            await user.list_permission(bot, args, chat_id)
            return

        elif args == "help":
            await bot.sendMessage(
                chat_id, "/user new <name> <pass>: Create user\n" +
                "/user remove <name>: Remove user\n" +
                "/user setpass <name> <pass>: Change password\n" +
                "/user addperm <name> <perm>: Add permission\n" +
                "/user removeperm <name> <perm>: Remove permission\n" +
                "/user listperm <name> <perm>: List permissions")
            return

    elif cmd == "plugin":

        if args == "reload":

            if sender_id != secrets.MY_USER_ID:
                await bot.sendMessage(chat_id,
                                      "You have no permission to do that.")
                return

            plugin_reload_all()
            await bot.sendMessage(
                chat_id, "Loaded plugins: " + ' '.join(PLUGIN_LIST_NAMES))
            return
        elif args == "list":
            await bot.sendMessage(
                chat_id, "Available plugins: " + ' '.join(PLUGIN_LIST_NAMES))
            return
        elif args == "help":
            await bot.sendMessage(
                chat_id, "/plugin reload: Reload plugins.\n" +
                "/plugin list: List available plugins.")
            return

    elif cmd == "cmd":

        if sender_id != secrets.MY_USER_ID:
            await bot.sendMessage(chat_id,
                                  "You have no permission to do that.")
            return

        shell_cmd = args

        if len(shell_cmd) > 0:
            (rc, stdout, stderr) = await utils.execute_shell_command(shell_cmd)
            if rc != None:
                if rc != 0 or ((len(stdout) == 0) and (len(stderr) == 0)):
                    await utils.send_message(bot, chat_id, "rc = " + str(rc))
                if len(stdout) > 0:
                    await utils.send_message(bot, chat_id, stdout)
                if len(stderr) > 0:
                    await utils.send_message(bot, chat_id, "stderr")
                    await utils.send_message(bot, chat_id, stderr)
        else:
            await bot.sendMessage(chat_id, "No command for shell found.")
        return

    elif cmd in PLUGIN_LIST_NAMES:
        index = PLUGIN_LIST_NAMES.index(cmd)
        try:
            method_to_call = getattr(PLUGIN_LIST[index], 'execute')
            await method_to_call(bot, msg, chat_id, args, sender_name)
        except:
            await utils.send_message(
                bot, chat_id, "Plugin command exception:\n" +
                textwrap.indent(str(sys.exc_info()[0]), "      ") + "\n" +
                textwrap.indent(str(sys.exc_info()[1]), "      "))
        return

    await bot.sendMessage(chat_id, "Command not found.")
    return