Ejemplo n.º 1
0
def getUserInfo(db, data):

    if "id" in data:
        data = db.getUser(data["id"])
    else:
        data = db.getUser(None, data["name"])
    return jsonify(data)
Ejemplo n.º 2
0
def complete():
    if "user" in session:
        tour = db.getUser(getUser())[0][4]
        stages = len(db.getTour(tour)[0][2])
        db.editPoints(getUser(),stages*5)
        points = db.getUser(session["user"])[0][3]
        db.addCurrentTourtoUser(getUser(),"None")
        return render_template("complete.html", points=points, epoints=(stages*5))
    return redirect(url_for("index"))
Ejemplo n.º 3
0
def home():
    if "user" in session:
        currentStage = "None"
        currentCity = "None"
        points = db.getUser(session["user"])[0][3]
        currentTour = db.getUser(session["user"])[0][4]
        if currentTour != "None":
            currentCity = db.getTour(currentTour)[0][7]
            currentStage = db.getUser(session["user"])[0][5]
        print geturl()
        return render_template('homepage.html', title="Welcome", currentTour = currentTour, user = getUser(), points = points, currentCity = currentCity, currentStage = currentStage)
    else:
        return redirect(url_for("index"))
Ejemplo n.º 4
0
def touroverview(city, tour):
    if "user" in session:
        description = db.getTour(tour)[0][1]
        points = db.getUser(session["user"])[0][3]
        image = db.getTour(tour)[0][8]
        if request.method == "POST":
            db.addCurrentTourtoUser(getUser(),tour)
            stage = str(db.getUser(getUser())[0][5])
            hidden = "True"
            #return redirect(url_for("home"))
            return redirect("/"+city+"/"+tour+"/"+tour+"/"+stage+"/"+hidden)
        return render_template('touroverview.html', city=city, tour=tour, description = description, image = image, points = points, title = tour)
    else:
        return redirect(url_for("index"))
Ejemplo n.º 5
0
    async def upgrade(self, ctx):
        """Displays currently available perks/classes"""
        currentUser = ctx.author.name
        user = db.getUser(ctx.author.id, ctx.author.guild.id)
        if user["level"] < 3 or (user["level"] % 3 == 1
                                 and user["is_upgraded"] == 1):
            self.roleMessage = await ctx.send(
                "You're not a high enough level yet!")

        # Class picking is a one-time thing for now
        elif user["level"] >= 3 and user["is_upgraded"] == 0:
            self.roleMessage = await ctx.send(
                "React with one of the emotes corresponding to the class you want, {}:\n:one: : Mage\n:two: : Warrior\n:three: : Archer"
                .format(currentUser))
            for key, value in self.emoteClasses.items():
                await self.roleMessage.add_reaction(value)

        # Perks are roles assigned to the user [Right now they can't be stacked]
        elif user["level"] % 3 == 0 and user["level"] > 3 and user[
                "is_upgraded"] == 1:
            self.roleMessage = await ctx.send(
                "React with one of the emotes corresponding to the perk you want, {}:\n⚔️ : Damage up\n🛡️ : Defense up\n❤️ : Health up"
                .format(currentUser))
            for key, value in self.emotePerks.items():
                await self.roleMessage.add_reaction(value)
Ejemplo n.º 6
0
def tours():
    if "user" in session:
        listOfCities = db.getCityList()
        points = db.getUser(session["user"])[0][3]
        return render_template('manyCities.html', title="Choose a City", listOfCities=listOfCities, points = points)
    else:
        return redirect(url_for("index"))
Ejemplo n.º 7
0
def my_expertise():
        if 'social-login' not in session:
            flash('You need to be authenticated in order to fill your expertise.', 'error')
            return redirect(url_for('login'))
        social_login = session['social-login']
        userid = social_login['userid']
        if request.method == 'GET':
            userProfile = db.getUser(userid)
            print userProfile
            userExpertise = userProfile['skills']
            return render_template('my-expertise.html', **{ 'AREAS': CONTENT['areas'],
                'userExpertise': userExpertise})
        if request.method == 'POST':
            userExpertise = json.loads(request.form.get('my-expertise-as-json'))
            session['user-expertise'] = userExpertise
            db.updateExpertise(userid, userExpertise)
            flash("""Your expertise has been updated.<br/>
            What you can do next:
            <ul>
            <li><a href="/search">Search for innovators</a></li>
            <li>Fill another expertise questionnaire below</li>
            <li>View your <a href="/user/%s">public profile</a></li>
            """ % social_login['userid'])
            session['has_filled_expertise'] = True
            #return render_template('my-expertise.html', **{'userExpertise': userExpertise, 'AREAS': CONTENT['areas']})
            return redirect(url_for('main_page'))
Ejemplo n.º 8
0
def group_message(message):
    chatObj = db.getChat(message.chat.id)
    usersThisChat = chatObj['users']
    if "/ImIn" in message.text and message.from_user.id not in usersThisChat:
        usersThisChat.append(message.from_user.id)
        updateObj = {'$set': {'users': usersThisChat}}
        db.setChatField(message.chat.id, updateObj)
        chatObj = db.getChat(message.chat.id)
        bot.reply_to(
            message, """\
                    حالا به @WorldCup1818bot برو و /openbets را وارد کن.

Now let's go to @WorldCup1818bot and enter /openbets.
                    \
                    """)
    elif 'WorldCup1818bot' in message.text:
        bot.reply_to(message, 'Let\'s continue in private @WorldCup1818bot!')
    if usersThisChat == []:
        try:
            bot.send_message(
                message.chat.id,
                """\برای پیش‌بینی نتایج بازی‌های جام‌جهانی به @WorldCup1818bot رفته و برای رقابت با دیگر اعضای گروه /ImIn را فشار دهید.
            To Participate in WorldCup2018 Prediction Contest, Join @WorldCup1818bot and Press /ImIn here.
            \
            """)
        except:
            pass
    userObj = db.getUser(message.chat.id, message.from_user.id)
Ejemplo n.º 9
0
def add():
    if 'user' not in session:
        session['return_to']='/settings'
        return redirect('/login')
    else:
        if request.method=='GET':
            return render_template('add.html',user=True,name=db.getUser(session['user']))
        else:
            placename = request.form['placename']
            lat = request.form['lat']
            lng = request.form['lng']
            adderID = db.getUser(session['user'])['oid']
            imgsrc = "notyet" ## possible enhancement for the future
            db.addPlace(placename, lat, lng, adderID, imgsrc)
            flash("Thank You")
            return redirect('/')
Ejemplo n.º 10
0
    async def buy(self, ctx, item):
        '''Buy an item from the shop'''
        currentItem = db.getItem(item)
        userId = ctx.author.id
        guildId = ctx.guild.id
        currentUser = db.getUser(userId, guildId)
        timeBought = datetime.datetime.now().timestamp()

        userItem = db.getUserItem(currentItem["item_id"], userId, guildId)

        if userItem is not None:
            await ctx.send(
                "You already have that item, you can only own one of each item!"
            )
            return 0

        if currentUser["currency"] < currentItem["item_price"]:
            await ctx.send("You do not have enough money to buy this item!")
            return 0

        db.modifyCurrency(userId, guildId, currentItem["item_price"] * -1)
        db.insertBoughtItem(currentItem["item_id"], userId, guildId,
                            timeBought)
        await ctx.send("Succesfully bought the {}".format(
            currentItem["item_name"]))
Ejemplo n.º 11
0
def search():
    if request.method=='GET':
        return render_template('search.html', name=db.getUser(session['user']))
    else:
        if request.form['submit']=='Search': ##search by keywords
            ## get the query from the HTML form
            query = request.form['holeInTheWall']
            print "The query is '%s'"%query
            ## get the places from the database
            places = db.getPlaces()
            ## sort the dictionary into a list
            results = findPlaces(places,query)
            ##results = ['I don\'t ','know what ','should go here - ','what\'s our search algorithm?']## ???
            ## pass sorted list to template
            return render_template('search.html',places=places, results=results, name=db.getUser(session['user']))
        else: ##search by location
            ##get ip address
            ip = urllib2.urlopen('http://ip.42.pl/raw').read()
            #get geo data
            URL = "http://www.freegeoip.net/json/" + ip
            req = requests.get(URL)###req= urllib2.urlopen(URL)###
            result = req.text###result = req.read()###
            data = json.loads(result)
            resultList = data.values()
            dump = ast.literal_eval(json.dumps(data))
            lat = dump.get("latitude")
            lng = dump.get("longitude")
            places = db.getPlaces()
            results = findPlacesByGeo(places,lat,lng)
            return render_template('search.html',places=places, results=results, name=db.getUser(session['user']))
Ejemplo n.º 12
0
def addBuild(db, user_name, tour_name, file, builder_name):
    result = {"ok": True, "msg": ''}
    cur_time = time.time()
    user_info = db.getUser(name=user_name)[0]
    tour_info = db.getTournament(name=tour_name)[0]
    o_path = make_out_path(tour_info["id"], user_info["id"], str(cur_time))
    os.makedirs(o_path)
    builder = util.register.builders[builder_name]
    src_path = os.path.join(o_path, builder.def_src_name)

    fileparams = 'w'
    if type(file) == bytes:
        fileparams += 'b'
    with open(src_path, fileparams) as src_file:
        src_file.write(file)
    b_stat = 0
    o_file = ""
    try:
        o_file = builder.build(src_path, o_path)
    except util.exceptions.BuildFailedException as e:
        b_stat = 1
        result["ok"] = False
        result["msg"] = str(e)

    db.addSolution(user_info["id"], tour_info["id"], b_stat, str(cur_time), builder_name, o_file)
    return result
Ejemplo n.º 13
0
def manageAccount(response):
    userid = response.get_secure_cookie('user_id')
    fail = response.get_field('fail', '') == '1'
    user = db.getUser(dbConn, userid)
    usertype = response.get_secure_cookie('user_type')
    response.write(TemplateAPI.render("manageAccount.html",
                                      response, {"title": "Account", "user": user, "fail":  fail, "usertype": usertype}))
Ejemplo n.º 14
0
def addEmail():
	global EMAIL_VALIDATOR
	auth = request.authorization
	user = db.getUser(auth.username)
	email = request.get_data(as_text=True)

	if user is None:
		return forbidden()

	if EMAIL_VALIDATOR.match(email) is None:
		return 'Invalid email', 400

	pw_hash = scrypt.hash(auth.password, user.get('pass_salt'))

	if pw_hash == user.get('pass_hash'):
		# Create an email verify code
		code = makeUniqueCode()
		db.addEmailCode(code, user.get('id'), email)

		# TODO we're hard coding this link for now
		link = 'https://funbox.com.ru:20100/update/email/confirm/' + code
		sendmail(email, 'Funbox Email Verification',
			'Hello from funbox! Use this link to verify your email: ' + link)

		return ok()
	else:
		return forbidden()
Ejemplo n.º 15
0
def addBuild(db, user_name, tour_name, file, builder_name):
    result = {"ok": True, "msg": ''}
    cur_time = time.time()
    user_info = db.getUser(name=user_name)[0]
    tour_info = db.getTournament(name=tour_name)[0]
    o_path = make_out_path(tour_info["id"], user_info["id"], str(cur_time))
    os.makedirs(o_path)
    builder = util.register.builders[builder_name]
    src_path = os.path.join(o_path, builder.def_src_name)

    fileparams = 'w'
    if type(file) == bytes:
        fileparams += 'b'
    with open(src_path, fileparams) as src_file:
        src_file.write(file)
    b_stat = 0
    o_file = ""
    try:
        o_file = builder.build(src_path, o_path)
    except util.exceptions.BuildFailedException as e:
        b_stat = 1
        result["ok"] = False
        result["msg"] = str(e)

    db.addSolution(user_info["id"], tour_info["id"], b_stat, str(cur_time),
                   builder_name, o_file)
    return result
Ejemplo n.º 16
0
def login():
    if request.method == 'POST':
        email_id = request.form['email_id']
        password = request.form['password']
        
        debug('Before trying to login with email_id '+email_id)

        username = db.logMeIn(g.db,email_id,password)
        
        if username:
            debug('Login successful for email_id : '+email_id)
            
            user = db.getUser(g.db, username)
            
            if user:
                session['username'] = user['username']
                debug('user found and session populated with : '+user['username'])
            else:
                error = "User population failed"
                return redirect(url_for('login', error = error))
                
            return redirect(url_for('queue'))
        else:

            error = 'Login failed. Try again'
            return render_template('login.html',error = error)
    else:
        return render_template('login.html')
Ejemplo n.º 17
0
def users(id):
    if request.method == 'GET':
        return getUser(id)
    elif request.method == 'PUT':
        return alterUser(id, request)
    elif request.method == 'DELETE':
        return deleteUser(id)
Ejemplo n.º 18
0
        def modifiedUpdated():
            nonlocal added_user
            sleep(1)  # Delay to ensure modified time is different
            db.updateUser(added_user)

            update_user = db.getUser(test_name)
            assert_that(update_user.get('updated_at'),
                        not_(equal_to(added_user.get('updated_at'))))
Ejemplo n.º 19
0
def vcard(userid):
    user = db.getUser(userid)
    if user:
        card = make_vCard(user['first_name'], user['last_name'], user['org'], user['title'], user['email'], user['city'], user['country'])
        return Response(card, mimetype='text/vcard')
    else:
        flash('This is does not correspond to a valid user.')
        return redirect(url_for('main_page'))
Ejemplo n.º 20
0
        def createdNotUpdated():
            nonlocal added_user
            sleep(1)  # Same here
            db.updateUser(added_user)

            update_user = db.getUser(test_name)
            assert_that(update_user.get('created_at'),
                        equal_to(added_user.get('created_at')))
Ejemplo n.º 21
0
def running(city, tour, tour1, stage, hidden):
    newstage = db.getUser(getUser())[0][5]
    points = db.getUser(session["user"])[0][3]
    print newstage
    stages = len(db.getTour(tour)[0][2]) - 1
    if newstage == "Begin":
        newstage = 0
    if int(newstage) == stages + 1:
        newstage = "End"
    if newstage == "End":
        return redirect("complete")
    newstage = int(newstage)
    clue = db.getTour(tour)[0][2][newstage]
    hint = db.getTour(tour)[0][3][newstage]
    latitude = db.getTour(tour)[0][5][newstage][0]
    print latitude
    longitude = db.getTour(tour)[0][5][newstage][1]
    # hint = db.getTour(tour)[0][3][newstage]
    print db.getUser(getUser())[0][5]
    if request.method == "POST":
        if request.form.has_key("hint"):
            db.editPoints(getUser(),-2)
            hidden = "False"
            sstage = str(newstage)
            return redirect("/"+city+"/"+tour+"/"+tour1+"/"+sstage+"/"+hidden)
        else:
            db.goToNextStage(getUser(),tour)
            print db.getUser(getUser())[0][5]
            sstage = str(db.getUser(getUser())[0][5])
            hidden = "True"
            return  redirect("/"+city+"/"+tour+"/"+tour1+"/"+sstage+"/"+hidden)
    return render_template('runningtour.html', city=city, tour=tour, stage=newstage, hidden=hidden, clue = clue, stages = stages, latitude = latitude, longitude = longitude, points = points, title = tour, hint = hint)
Ejemplo n.º 22
0
def login():
    print session
    if request.method == 'GET':
        return render_template('login-page.html', **{'SKIP_NAV_BAR': False})
    if request.method == 'POST':
        social_login = json.loads(request.form.get('social-login'))
        session['social-login'] = social_login
        userid = social_login['userid']
        userProfile = db.getUser(userid)
        if userProfile:
            session['user-profile'] = userProfile
        else:
            db.createNewUser(userid, social_login['first_name'], social_login['last_name'], social_login['picture'])
            userProfile = db.getUser(userid)
            session['user-profile'] = userProfile
        flash('You are authenticated using your %s Credentials.' % social_login['idp'])
        g.is_logged_in = True
        return jsonify({'result': 0})
Ejemplo n.º 23
0
def user(id=None, dn=None):
    api_version,root_url,root=get_api_version(request.url)
    #Unregistered users need to be able to be registered, hence comment this out for now.
    #A better solution is to have a valid user register unregistered users. This could be
    #the UI itself.

    istatus=200
    if request.method == 'POST':
        r = rdb.addUser( request.data, submitter_dn=dn )
        if not r: istatus=404
    elif request.method == 'GET':
        if id:
            r = rdb.getUser( {'uid':id}, dn=dn )
        else:
            r = rdb.getUser( request.args, dn=dn )
            if apidebug: print('APIDEBUG user route:: dn = ',dn)

    return Response(json.dumps(r,cls=MPOSetEncoder), mimetype='application/json',status=istatus)
Ejemplo n.º 24
0
def show_candidate(slug=None):
    """
    """
    if slug is None:
        return "Candidate not provided"

    candidate = db.get_candidate(slug)
    if candidate is None:
        return "Candidate not found"

    full_name = get_full_name(candidate['name'])

    twitter_user = db.getUser(candidate.get('twitter_handle'))
    twitter_data = None
    followers = {"numFollowers": None, "numBots": None, "numHumans": None}
    word_cluster = {'topics': []}
    if twitter_user:
        twitter_data = {"profile_url": twitter_user["twitter"]["profile_image_url_https"]}
        followers["numFollowers"] = twitter_user["twitter"]["followers_count"]
        follower_stats = db.getFollowerStats(candidate['twitter_handle'])
        followers.update(follower_stats)
        word_frequencies = twitter_user.get('word_frequencies')
        if word_frequencies:
            word_cluster = word_frequencies

    election = candidate['election']
    district = db.get_district(election['district'])
    election['district'] = {'id': district['_key'], 'name': district['name']}

    json_output = {
        "content": "MEMBER", 
        "member": {
            "name": full_name,
            "twitter_handle": candidate.get('twitter_handle'),
            "facts" : candidate["facts"],
            "links" : candidate["links"],
            "photos" : candidate["photos"]
        },
        "twitter": twitter_data,
        "wordCluster": word_cluster,
        "followers": followers,
        "retweets": {
              "numRetweets": None,
              "numHumans": None,
              "numBots": None
        },
        "retweeters": {
              "numRetweeters": None,
              "numHumans": None,
              "numBots": None
        },
        "election": election,
        "botness": twitter_user["botness"] if twitter_user and "botness" in twitter_user else {}
    }

    return jsonify(json_output)
Ejemplo n.º 25
0
def edit_user(userid):
    if request.method == 'GET':
        userProfile = db.getUser(userid)  # We get some stuff from the DB.
        return render_template('my-profile.html', **{'userProfile': userProfile })
    if request.method == 'POST':
        userProfile = json.loads(request.form.get('me'))
        session['user-profile'] = userProfile
        db.updateCoreProfile(userProfile)
        flash('Your profile has been saved.')
        return render_template('my-profile.html', **{'userProfile': userProfile})
Ejemplo n.º 26
0
def send_delays():
    if session['user']:
        if mta.service_status().has_delays():
            message = 'there are some f*****g delays'
        else:
            message = 'there are no f*****g delays'

        user = db.getUser(session['user'])
        sms.send_message(message, int(user['phone']))
    return redirect("/")
Ejemplo n.º 27
0
    async def steal(self, ctx, member: discord.Member):
        if ctx.author.name == member.name:
            await ctx.send(
                "You try to steal money from yourself... It doesn't work.")
            return 0

        userId = ctx.author.id
        guildId = ctx.author.guild.id
        user = db.getUser(userId, guildId)
        enemyUser = db.getUser(member.id, member.guild.id)
        lastStolen = datetime.datetime.now().timestamp()

        if user["last_stolen"] != "":
            timeSinceLastSteal = lastStolen - float(user["last_stolen"])

        else:
            timeSinceLastSteal = self.stealCooldown + 1

        if user["last_stolen"] != "" and timeSinceLastSteal < self.stealCooldown:
            await ctx.send(
                "You cannot steal at this time, you must wait {:.2f} hours.".
                format((self.stealCooldown - timeSinceLastSteal) / 3600))
            return 0

        if db.getUserItem(3, userId, guildId) is not None:
            if randint(1, 100) >= 50:
                moneyLost = randint(50, 150) * -1
                if enemyUser["currency"] + moneyLost < 0:
                    moneyLost = enemyUser["currency"] * -1
                db.modifyCurrency(member.id, guildId, moneyLost)
                db.modifyCurrency(userId, guildId, moneyLost * -1)
                db.updateStealTiming(userId, guildId, str(lastStolen))
                await ctx.send(
                    "You succesfully steal money from {}, you gain ${}!".
                    format(member.name, moneyLost * -1))
            else:
                await ctx.send(
                    "You try to steal money from {}, you fail to do so.".
                    format(member.name))
        else:
            await ctx.send(
                "You do not own the appropriate item to use this command. Do $shop to see what items are for sale."
            )
Ejemplo n.º 28
0
def send_welcome(message):
    bot.reply_to(
        message, """\
سلام، بات پیش‌بینی جام‌جهانی ۲۰۱۸ هستم!
برای آشنایی و نحوه‌ی امتیاز دهی /help را انتخاب کنید.
برای پیش‌بینی مسابقات امروز /openbets را انتخاب کنید.

You can change the language to English by pressing /english!
\
""")
    userObj = db.getUser(message.chat.id, message.from_user.id)
    if userObj['first'] == []:
        updateObj = {'$set': {'first': message.from_user.first_name}}
        db.setUserFields(message.chat.id, message.from_user.id, updateObj)
    if userObj['last'] == []:
        updateObj = {'$set': {'last': message.from_user.last_name}}
        db.setUserFields(message.chat.id, message.from_user.id, updateObj)
    userObj = db.getUser(message.chat.id, message.from_user.id)
    print(userObj)
Ejemplo n.º 29
0
def user(id=None, dn=None):
    api_version, root_url, root = get_api_version(request.url)
    #Unregistered users need to be able to be registered, hence comment this out for now.
    #A better solution is to have a valid user register unregistered users. This could be
    #the UI itself.

    istatus = 200
    if request.method == 'POST':
        r = rdb.addUser(request.data, submitter_dn=dn)
        if not r: istatus = 404
    elif request.method == 'GET':
        if id:
            r = rdb.getUser({'uid': id}, dn=dn)
        else:
            r = rdb.getUser(request.args, dn=dn)
            if apidebug: print('APIDEBUG user route:: dn = ', dn)

    return Response(json.dumps(r, cls=MPOSetEncoder),
                    mimetype='application/json',
                    status=istatus)
Ejemplo n.º 30
0
def review(oid=1):
    if request.method=='GET':
        places = db.getPlaces()
        oid = int(oid)
        return render_template('reviews.html', oid=oid, place=db.getPlaces()[oid], name=db.getUser(session['user']), reviews=db.getReviews(oid), users=db.getUsers(), plat = float(places[oid]['lat']), plng = float(places[oid]['lng']))
    else:
        ## get the review from the HTML form
        rating = request.form['stars']
        content = request.form['myTextBox']
        authorID = db.getUser(session['user'])['oid'] 
        title = "no title" ## no comment title in HTML form
        placeID = oid
        ## add comment to database
        db.addReview(title,content,int(rating),authorID,placeID)
        ## flash success
        flash('Thank you for your review!')
        ## return template
        places = db.getPlaces()
        oid = int(oid)
        return render_template('reviews.html', oid=oid, place=places[oid], name=db.getUser(session['user']), reviews=db.getReviews(oid), users=db.getUsers(), plat = float(places[oid]['lat']), plng = float(places[oid]['lng']))
Ejemplo n.º 31
0
def detail_points(userId):
    userObj = db.getUser(userId, userId)
    points = userObj['points']
    a = []
    a.append(points.count(25))
    a.append(points.count(18))
    a.append(points.count(15))
    a.append(points.count(12))
    a.append(points.count(10))
    a.append(points.count(4))
    return a
Ejemplo n.º 32
0
        def updatedUser():
            nonlocal added_user
            update_email = '*****@*****.**'
            added_user['email'] = update_email
            res = db.updateUser(added_user)
            updated_user = db.getUser(test_name)

            assert_that(updated_user.get('name'), equal_to(test_name))
            assert_that(updated_user.get('pass_hash'), equal_to(test_hash))
            assert_that(updated_user.get('pass_salt'), equal_to(test_salt))
            assert_that(updated_user.get('email'), equal_to(update_email))
Ejemplo n.º 33
0
def home():
	if 'usern' not in session:
		return render_template('home.html')
	user = db.getUser(usern=session['usern'])
	if not user:
		session.pop('usern', None)
		return render_template('home.html')

	d = {}
	d['usern'] = session['usern']
	d['repos'] = github.get('user/repos')
	return render_template('dashboard.html', d=d)
Ejemplo n.º 34
0
def OAUTH_USERID(token):
    url = "https://api.github.com/user"
    oauthresponse = requestUser(url, token)
    userId = oauthresponse['login']

    strrrrUserId = db.getUser(userId)
    if strrrrUserId == 0:
        print("no id!!! making a new one")
        db.setToken(userId, token)
        db.createTable(userId)
    else:
        pass
    return userId
Ejemplo n.º 35
0
def get_user(userid):
    user = db.getUser(userid)
    if user:
        if 'social-login' in session:
            my_userid = session['social-login']['userid']
        else:
            my_userid = 'anonymous'
        query_info = {'user-agent': request.headers.get('User-Agent'), 'type': '/user', 'userid': my_userid}
        db.logQuery(my_userid, query_info)
        return render_template('user-profile.html', **{'user': user, 'userid': userid, 'SKILLS': []})
    else:
        flash('This is does not correspond to a valid user.')
        return redirect(url_for('search'))
Ejemplo n.º 36
0
def my_points(message):
    allUsers = db.loadAllUsers()
    sortedUsers = sorted(allUsers, key=itemgetter('score'), reverse=True)
    highest_score = sortedUsers[0]['score']
    userId = message.from_user.id
    user = db.getUser(userId, userId)
    if user['lang'] == "fa":
        msg_text = 'شما تا اینجا '
        msg_text += str(user['score'])
        msg_text += ' امتیاز کسب کرده‌اید و در رتبه‌ی '
        msg_text += str(user['rank'])
        msg_text += ' قرار دارید.\nبیشترین امتیاز: '
        msg_text += str(highest_score)
    else:
        msg_text = 'You have earned '
        msg_text += str(user['score'])
        msg_text += ' so far. Your overall rank is: '
        msg_text += str(user['rank'])
        msg_text += '\nHighest Score: '
        msg_text += str(highest_score)
    bot.reply_to(message, msg_text)
    temp = detail_points(user['userId'])
    detail_table_msg = 'Rank   Name\n \t \t \tES WG GD LG CW T TOT\n-----------------------------------\n'
    detail_table_msg += str(user['rank']) + '. '
    if isinstance(user['first'], str):
        detail_table_msg += user['first'] + ' '
    if isinstance(user['last'], str):
        detail_table_msg += user['last']
    detail_table_msg += '\n \t \t \t ' + str(temp[0]) + '   ' + str(
        temp[1]) + '   ' + str(temp[2]) + '   ' + str(temp[3]) + '   ' + str(
            temp[4]) + '   ' + str(temp[5]) + '   ' + str(user['score'])
    if (user['lang'] == "fa"):
        detail_table_msg += '\n\nES: نتیجه‌ی دقیق'
        detail_table_msg += '\nWG: تعداد گل برنده'
        detail_table_msg += '\nGD: اختلاف گل'
        detail_table_msg += '\nLG: تعداد گل بازنده'
        detail_table_msg += '\nCW: برنده‌ی صحیح'
        detail_table_msg += '\nT: مساوی'
        detail_table_msg += '\nTOT: جمع امتیازات'
    else:
        detail_table_msg += '\n\nES: Exact Score'
        detail_table_msg += '\nWG: Winner\'s Goals'
        detail_table_msg += '\nGD: Goal Difference'
        detail_table_msg += '\nLG: Loser\'s Goals'
        detail_table_msg += '\nCW: Correct Winner'
        detail_table_msg += '\nT: Tie'
        detail_table_msg += '\nTOT: Total Points'
    try:
        bot.send_message(chat_id=user['userId'], text=detail_table_msg)
    except:
        pass
Ejemplo n.º 37
0
def city(city):
    if city not in db.getCityList():
        return redirect(url_for("error"))
    if "user" in session:
        points = db.getUser(session["user"])[0][3]
        tours = db.getTourList(city)
        count = len(tours)
        images = []
        for tour in tours:
            img = db.getTour(tour)[0][8]
            images.append(img)
        return render_template('city.html', city = city, tours = tours, images = images, points = points, count = count, title = city)
    else:
        return redirect(url_for("index"))
Ejemplo n.º 38
0
def post_route(username):
    try:
        if request.method == 'GET':
            return jsonify(db.getUser(username))
        elif request.method == 'DELETE':
            return jsonify(db.deleteUser(username))
        # there isn't much to modify anyway for specifically a user
        # elif request.method == 'PUT':
        #     user = request.get_json()
        #     if user == None:
        #         return returnError(400, 'missing body')
        #     return jsonify(db.editUser(username, user))
    except:
        return returnError(404, 'user not found')
Ejemplo n.º 39
0
def verifyUser():
	auth = request.authorization
	user = db.getUser(auth.username)

	# Return 403 instead of a 404 to make list of users harder to brute force
	if user is None:
		return forbidden()

	pw_hash = scrypt.hash(auth.password, user.get('pass_salt'))

	if pw_hash == user.get('pass_hash'):
		return ok()
	else:
		return forbidden()
Ejemplo n.º 40
0
def signup():
    if request.method == 'POST':
        form = request.form
        if db.addUser(form['username'], form['email'], form['password']):
            user = db.getUser(form['email'], 'email')
            login_user(User(user))
            return redirect('/')
        else:
            return render_template('roddit.html', type='signup', fail=True)
    else:
        if current_user.is_authenticated:
            return redirect('/')
        else:
            return render_template('roddit.html', type='signup', fail=False)
Ejemplo n.º 41
0
def signIn():
    data = request.get_json()
    userId = data.get("user_id")
    password = data.get("password")

    if None in [userId, password]:
        return json.dumps({
            "error": "Invalid request",
            "status": "failure"
        }), 400

    authUserRes = authenticateUserCredentials(userId, password)
    if not authUserRes.get("status"):
        return json.dumps({
            "error": authUserRes.get("error"),
            "status": "unauthorized"
        }), 401

    access_token = generateAccessToken(userId)
    userDataRes = getUser(userId)
    if not userDataRes.get("status"):
        return app.response_class(response=json.dumps({
            "status":
            "failure",
            "error":
            userDataRes.get("error")
        }),
                                  mimetype="application/json"), 400

    userData = userDataRes.get("data")
    userData.update({
        "access_token": access_token,
        "token_type": "JWT",
        "expires_in": JWT_LIFE_SPAN,
    })

    return (
        app.response_class(
            response=json.dumps(
                {
                    "status": "success",
                    "error": None,
                    "data": userData
                },
                default=json_util.default),
            mimetype="application/json",
        ),
        200,
    )
Ejemplo n.º 42
0
def candidate_info(slug=None):
    """
    """
    if slug is None:
        return "Candidate not provided"

    candidate = db.get_candidate(slug)
    if candidate is None:
        return "Candidate not found"

    full_name = get_full_name(candidate['name'])

    twitter_user = db.getUser(candidate['twitter_handle'])
    if twitter_user is None:
        return "Twitter user for candidate lost in the dark forest - make a donation to us to find this user."

    followers = {"numFollowers": twitter_user["twitter"]["followers_count"]}
    follower_stats = db.getFollowerStats(candidate['twitter_handle'])
    followers.update(follower_stats)

    json_output = {
        "content": "MEMBER",
        "facts": candidate["facts"],
        "links": candidate["links"],
        "photos": candidate["photos"],
        "member": {
            "name": full_name,
            "pictureURL": '',
            "party": candidate["election"]["party"],
            "twitter_handle": candidate['twitter_handle']
        },
        "wordCluster": twitter_user.get("word_frequencies"),
        "followers": followers,
        "retweets": {
            "numRetweets": 12,
            "numHumans": 11,
            "numBots": 1
        },
        "retweeters": {
            "numRetweeters": 22,
            "numHumans": 9,
            "numBots": 13
        },
        "election": candidate['election'],
        "botness":
        twitter_user["botness"] if "botness" in twitter_user else {}
    }

    return jsonify(json_output)
Ejemplo n.º 43
0
def login():
    if request.method == "POST":
        form = request.form
        user_id = db.verifyUser(form["email"], form["password"])
        if user_id != None:
            user = db.getUser(user_id)
            login_user(User(user))
            return redirect("/")
        else:
            return render_template("login.html", error=True)
    else:
        if current_user.is_authenticated:
            return redirect("/")
        else:
            return render_template("login.html", error=False)
Ejemplo n.º 44
0
def index():
    if 'id' in session:
        user = db.getUser()
        #if user['wizard']:
        #    return redirect(url_for('settings.wizard'), code=302)
        #else:
        session.pop('preview_id', None)
        session.pop('preview_css', None)
        session.pop('editor_id', None)
        session.pop('editor_css', None)
        session.pop('editor_title', None)
        session['css'] = db.getUsersCSS()
        session['bookmarks'] = db.getBookmarks()
        return render_template('mypage.html')
    return render_template('index.html', name="name")
Ejemplo n.º 45
0
def my_profile():
    if request.method == 'GET':
        social_login = session['social-login']
        print "Looking up %s" % social_login['userid']
        userProfile = db.getUser(social_login['userid'])  # We get some stuff from the DB.
        print userProfile
        return render_template('my-profile.html', **{'userProfile': userProfile })
    if request.method == 'POST':
        userProfile = json.loads(request.form.get('me'))
        session['user-profile'] = userProfile
        db.updateCoreProfile(userProfile)
        flash('Your profile has been saved. <br/>You may also want to <a href="/my-expertise">tell us what you know</a>.')
        session['has_created_profile'] = True
        #return render_template('my-profile.html', **{'userProfile': userProfile})
        return redirect(url_for('main_page'))
Ejemplo n.º 46
0
def show_games(message):
    markup = types.ReplyKeyboardMarkup()
    userObj = db.getUser(message.chat.id, message.from_user.id)
    if message.text == '/changebet':
        wantToHaveNewBet = False
        wantToChangeBet = True
    else:
        wantToHaveNewBet = True
        wantToChangeBet = False
    matches = db.loadOpenMatches()

    openBets = []
    for match in matches:
        alreadyBet = False
        for bet in userObj['bets']:
            if bet['matchId'] == match['matchId']:
                alreadyBet = True
                break
        if (alreadyBet and wantToChangeBet) or (not alreadyBet
                                                and wantToHaveNewBet):
            openBets.append(match)

    open_text = "لطفاً بازی‌ موردنظر را انتخاب کنید یا برای تغییر نتیجه "
    open_text += "/changebet"
    open_text += " را فشار دهید:"
    open_text += '\nPlease choose the game you want to bet on or choose /changebet:'
    if openBets != []:
        for Obet in openBets:
            itembtn1 = Obet['flags']
            markup.row(itembtn1)
        try:
            bot.send_message(chat_id=message.from_user.id,
                             text=open_text,
                             reply_markup=markup)
        except Exception as e:
            logger.error(e)
            print('This user is causing trouble in show_games:')
            print(userObj)
    else:
        markup = types.ReplyKeyboardRemove(selective=False)
        bot.send_message(chat_id=message.from_user.id,
                         text="""\
        همه‌ی بازی‌ها را پیش‌بینی کردید! برای تغییر نتایج /changebet را انتخاب کنید.

You have no open bets. Press /changebet to change your bets.
                   \
                   """,
                         reply_markup=markup)
Ejemplo n.º 47
0
def settings():
    if 'user' not in session:
        session['return_to']='/settings'
        return redirect('/login')
    else:
        if request.method=='GET':
            return render_template('settings.html',name=db.getUser(session['user']))
        else:
            ##get new info and update
            user = session['user']
            pw = request.form['oldpw']
            newpw = request.form['newpw']
            if pw == "" or not db.updatePass(user,pw,newpw):
                flash("Please enter your correct current password to make any changes!")
                return redirect("/settings")
            else:
                return redirect('/about')
Ejemplo n.º 48
0
def create():
    city = ""
    points = db.getUser(session["user"])[0][3]
    cities = db.getCityList()
    if request.method == "POST":
        title = request.form["title"]
        description = request.form["description"]
        image = request.form["image"]
        city = request.form["selectedCity"]
        clues = []
        hints = []
        ratings = []
        reviews = []
        coordinates = []
        db.addTour(title, description, clues, hints, ratings, reviews, coordinates, city, image)
        return redirect("/"+title+"/create2/1")
    return render_template('create.html', cities = cities, points = points, title = "Create",city = city)
Ejemplo n.º 49
0
def gh_callback(oauth_token):
	# ensure we got the token
	if oauth_token is None:
		flash('There was an issue logging in')
		utils.log('err: login error')
		return redirect(url_for('home'))

	# if the user is new register them with the db
	if not db.hasUser(oauth_token):
		db.addUser(oauth_token)
	usern = db.getUser(oauth_token)['usern']

	# give them a cookie (or refresh theirs) that says logged-in
	session['usern'] = usern

	# send them to the dashboard
	flash('You were logged in')
	return redirect(url_for('home'))
Ejemplo n.º 50
0
def Login():
    if request.method == 'POST':
        email = str(request.form['email'])
        password = str(request.form['password'])
        button = request.form['button']
        if button == "Login":
            if email == "":
                return redirect(url_for("Error"))
            password2 = db.getPassword(email)
            broname = db.getUser(email)
            if password2 == password:
                return redirect(url_for("restaurantSearch", broname=broname))
            else:
                return redirect(url_for("Login"))
        if button == 'Signup':
            return redirect(url_for("Signup"))
    else:
        return render_template('Login.html')
Ejemplo n.º 51
0
def match():
    if 'user-expertise' not in session:
        flash('Before we can match you with fellow innovators, you need to <a href="/my-expertise">enter your expertise</a> first.', 'error')
        return redirect(url_for('main_page'))
    social_login = session['social-login']
    userid = social_login['userid']
    query = {'location': '', 'langs': [], 'skills': [], 'fulltext': ''}
    if 'skills' not in session['user-expertise']:
        userProfile = db.getUser(userid)
        userExpertise = userProfile['skills']
        session['user-expertise'] = userExpertise
    print "user expertise: ", json.dumps(session['user-expertise'])
    skills = session['user-expertise']
    my_needs = [k for k,v in skills.iteritems() if int(v) == -1]
    print my_needs
    experts = db.findMatchAsJSON(my_needs)
    session['has_done_search'] = True
    return render_template('search-results.html', **{'title': 'People Who Know what I do not', 'results': experts, 'query': query})
Ejemplo n.º 52
0
def signup():
    if request.method == "POST":
        form = request.form
        if form["password"] == form["repeatPassword"]:
            user_id = db.addUser(form["username"], form["email"],
                                 form["password"])
            if user_id != None:
                user = db.getUser(user_id)
                login_user(User(user))
                return redirect("/")
            else:
                return render_template("signup.html", error=True)
        else:
            return render_template("signup.html", error=True)
    else:
        if current_user.is_authenticated:
            return redirect("/")
        else:
            return render_template("signup.html", error=False)
Ejemplo n.º 53
0
def user():
    authResponse = authentication()
    if authResponse["statusCode"] == 200 and authResponse["isVerified"]:
        userId = authResponse.get("data").get("user_id")
        userDataRes = getUser(userId)
        if not userDataRes.get("status"):
            return app.response_class(response=json.dumps({
                "status":
                "failure",
                "error":
                userDataRes.get("error"),
            }),
                                      mimetype="application/json"), 400

        userData = userDataRes.get("data")
        userData.update({
            "access_token":
            request.headers.get("Authorization").split(" ")[1],
            "token_type":
            "JWT",
            "expires_in":
            JWT_LIFE_SPAN,
        })

        return app.response_class(
            response=json.dumps(
                {
                    "status": "success",
                    "error": None,
                    "data": userData,
                },
                default=json_util.default),
            mimetype="application/json"), authResponse["statusCode"]

    return app.response_class(
        response=json.dumps(
            {
                "status": "unauthorized",
                "data": None,
                "error": authResponse["error"]
            },
            default=json_util.default),
        mimetype="application/json"), authResponse["statusCode"]
Ejemplo n.º 54
0
def follower_botness(username):
#given a username, it creates the histogram of the botness of the followers 
#and saves it in plots (for now)  it also returns the probable percentage of follower bots
#(cutoff needs to be defined, for now it is 0.7)""" 
    cutoff = 0.7
    scorelist = []
    followers = db.getFollowers(toName=username)
    for f in followers:
        follower = f['_from'].split('/')[1]
        score = db.getUser(follower)['botness']['score']
        scorelist.append(score)

    if scorelist:
        scores = pd.Series(scorelist, name='probability of follower bot') 
        ax = sns.distplot(scores) 
        fig = ax.get_figure()
        fig.savefig('testfig.png')
        botpercent = sum(np.array(scorelist)>cutoff) / len(scorelist)
        return botpercent
    else:
        return None
Ejemplo n.º 55
0
def addBug():
    if 'username' in session:
        if request.method <> 'POST':
            return render_template('createbug.html')
        else:
            debug('Creating the bug dictionary for the username : '******'username'])
            user = db.getUser(g.db, session['username'])
            if user:
                
                user_id = user['user_id']
                
                debug('Building dictionary before creating bug for user_id : '+str(user_id))
                
                bug = dict(title = request.form['title'], customer=request.form['customer'], assigned_to_username = request.form['assigned_to_username'], description = request.form['description'], priority = request.form['priority'], status = 'OPEN', user_id = user_id)

                debug('Calling db.createBug2 for bug '+bug['title'])
                db.createBug2(g.db, bug)
                debug('Created the above bug')
                return redirect(url_for('queue'))
            else:
                return redirect(url_for('queue'))

    else:
        return render_template('login.html', error = 'Login first')
Ejemplo n.º 56
0
def home():
    if 'user' not in session:
        session['return_to']='/home'
        return redirect('/login')
    else:
        return render_template('home.html',name=db.getUser(session['user']))
Ejemplo n.º 57
0
def about():
    if 'user' not in session:
        return render_template('about.html')
    else:
        print session['user']
        return render_template('about.html',user=session['user'],name=db.getUser(session['user']))
def process_msg(msg , conn, socket, runtimeData):
    paras = msg.split(MESSAGE_SPLIT_TAG)
    msg_head = paras[0]
    tobekicked = []
    
    if(msg_head == "LOGIN"):
        user = paras[1]
        password = paras[2]
        u = db.getUser(user, conn)
        if(u != None and u[2] == password):
            send(socket,"LOGIN" + MESSAGE_SPLIT_TAG + "true")
            runtimeData["online"][socket] = u
            #踢掉当前在线的
            for u in runtimeData["online"]:
                username = runtimeData["online"][u][1]
                if(username==user and u != socket):
                    tobekicked.append(u)
        else:
            send(socket,"LOGIN" + MESSAGE_SPLIT_TAG + "false")
            tobekicked.append(socket)
            
    if(msg_head == "LOGOUT"):
        runtimeData["online"].remove(socket)
        tobekicked.append(socket)
    
    if(msg_head == "JOIN_CHANNEL"):
        channels = paras[1].split("#")
        runtimeData["channel"][socket] = channels
        send(socket, "JOIN_CHANNEL" + MESSAGE_SPLIT_TAG + "true")
    
    if(msg_head == "GET_ONLINE_USERS"):
        ret = "GET_ONLINE_USERS"
        for u in runtimeData["online"]:
            username = runtimeData["online"][u][1]
            score = int(runtimeData["online"][u][3])
            ret = ret + MESSAGE_SPLIT_TAG +  username + "," + str(score)
        send(socket,ret)
        
    if(msg_head == "CHAT"):
        channel = paras[1]
        info = paras[2]
        me_username = runtimeData["online"][socket][1]
        me_score = int(runtimeData["online"][socket][3])
        msg = "CHAT" + MESSAGE_SPLIT_TAG + me_username + "," + str(me_score) + MESSAGE_SPLIT_TAG + channel + MESSAGE_SPLIT_TAG + info.decode("utf-8")
        for u in runtimeData["channel"]:
            try:
                if channel in runtimeData["channel"][u] and u!=socket:
                    send(u, msg)
            except:
                pass
            
    if(msg_head == "GET_SAVES"):
        me_username = runtimeData["online"][socket][1]
        saves = []
        for s in db.getSaves(me_username, conn):
            if(s[1] != None):
                saves.append(s[1])
            else:
                saves.append("Empty")
        msg = "GET_SAVES"
        for s in saves:
            msg = msg + MESSAGE_SPLIT_TAG + s
        send(socket,msg)
        
    if(msg_head == "SAVE"):
        me_username = runtimeData["online"][socket][1]
        index = paras[1]
        content = paras[2]
        ret = db.save(me_username, index, content, conn)
        if ret :
            send(socket,"SAVE" + MESSAGE_SPLIT_TAG + "true")
        else:
            send(socket,"SAVE" + MESSAGE_SPLIT_TAG + "false")
            
    if(msg_head == "BATTLE_RESULT"):
        channel = paras[1]
        winner = paras[2]
        loser = paras[3]
        
        uwin = db.getUser(winner, conn)
        ulose = db.getUser(loser, conn)
        
        winner_score = (int)(uwin[3])
        loser_score = (int)(ulose[3])
        
        #积分规则
        if(winner_score - loser_score > 100): #差距100以上,忽略
            pass
        elif(winner_score >= loser_score):
            delta = winner_score - loser_score
            winner_score += 10 - delta / 10
            loser_score -= 10 - delta / 20
        elif(loser_score > winner_score):
            delta = loser_score - winner_score
            winner_score += 10
            loser_score -= 10
        
        db.updateScore(winner, winner_score, conn)
        db.updateScore(loser, loser_score, conn)
        
        for u in runtimeData["online"]:
            username = runtimeData["online"][u][1]
            if username == winner:
                runtimeData["online"][u] = db.getUser(winner, conn)
            if username == loser:
                runtimeData["online"][u] = db.getUser(loser, conn)
        
        send(socket, "BATTLE_RESULT" + MESSAGE_SPLIT_TAG + "true")        
    
    return tobekicked
Ejemplo n.º 59
0
def bug():
    bug_id = request.args.get('bug_id', '')
    if request.method <> 'POST':
        debug('Calling getBugHeader')
        bugh = db.getBugHeader(g.db, bug_id)
        debug('Calling getBugBody')
        bugb = db.getBugBody(g.db, bug_id)
        all_status = db.getStatuses(g.db)
        all_users = db.getUsers(g.db)
            
        return render_template('bug.html', bugh = bugh, bugb = bugb, all_status = all_status, all_users = all_users)
    
    else:
        debug('Creating dictionary of bug to update the header for '+str(bug_id))

        assigned_to_user_id = db.getUser(g.db, request.form['assigned_to_username'])['user_id']
        updating_user_id = db.getUser(g.db, session['username'])['user_id']
        
        bug = dict(title = request.form['title'], customer=request.form['customer'], updated_by_username = session['username'], assigned_to_user_id = assigned_to_user_id ,assigned_to_username = request.form['assigned_to_username'], description = request.form['description'], priority = request.form['priority'], status = request.form['status'], updating_user_id = updating_user_id, bug_id = bug_id)


        # creating list of header updates onto the body
        debug(str(bug_id))
        bugh = db.getBugHeader(g.db, bug_id)
    
        changedString = ""
        
        
        if bugh['title'] <> bug['title']:
            changedString += "** Changed Title from "+bugh['title']+" to "+ bug['title'] + "\n"

        #if bugh['description'] <> bug['description']:
        #    changedString += "** Changed Description from "+bugh['description']+" to "+ bug['description'] + "\n"

        if bugh['assigned_to_user_id'] <> bug['assigned_to_user_id']:
            to = db.getUserEmail(g.db,bug['assigned_to_user_id'])
            debug('Sending email to notify assignation to : '+to)
            changedString += "** Changed Assigned from "+ bugh['assigned_to_username'] + " to "+ request.form['assigned_to_username'] + "\n"
            debug (changedString)
            emails.bugAssignNotify(bug, to)

        if bugh['description'] <> bug['description']:
            changedString += "** Changed Bug Description from " + "\n" + bugh['description'] 

        if bugh['customer'] <> bug['customer']:
            changedString += "** Changed Customer from "+bugh['customer']+" to "+ bug['customer'] + "\n"

        if bugh['status'] <> bug['status']:
            changedString += "** Changed Status from "+bugh['status']+" to "+ bug['status'] + "\n"

        if str(bugh['priority']) <> str(bug['priority']):
            changedString += "** Changed Priority from "+str(bugh['priority'])+" to "+ str(bug['priority']) + "\n"
            
        debug(changedString)    
        # Now updating the header with changes
        db.updateBugHeader(g.db, bug)

        newUpdate = changedString + "\n" + request.form['newupdate']
        bugUpdate = dict(update = newUpdate, updated_by_user_id = updating_user_id, bug_id = bug_id)

        db.insertBugUpdate(g.db, bugUpdate)
        
        return redirect(url_for('queue'))