Esempio n. 1
0
def users_view():
    if session.get("username") is None:
        return redirect("/login/")
    user_id = request.args.get("id")
    name = models.get_user(user_id).get('name')
    age = models.get_user(user_id).get('age')
    department = models.get_user(user_id).get("department")
    inro = models.get_user(user_id).get("inro")
    hobby_list = models.get_user(user_id).get("hobby")
    hobby = (hobby_list).split(",")
    return render_template("user_edit.html", user_id = user_id, name = name, age = age, \
    hobby = hobby_list, department = department, inro = inro, username =session.get("username"))
Esempio n. 2
0
def extract_lines_times(lat, lon, user_id):
    """
    Extract timetables by a stop, retrieving first available stops, using the method above. 
    It matches the user destination informations previously stored in the datastore, 
    with the data retrieved here, in order to propose the smartest solution ever. 

    @param lat: the latitude of user location
    @param lon: the longitude of user location
    @param user_id: the user id, used to retrieve user destination info
    """
    lines_updated_stop = get_stops(lat, lon, lines=False)
    lines_updated = lines_updated_stop["ListaLinee"]
    stop_id = lines_updated_stop["IdFermata"]
    stop_address = lines_updated_stop["DescrizioneFermata"]
    distance_mt = lines_updated_stop["DistanzaMetri"]

    user = get_user(user_id)
    lines_original = json.loads(user.lines)
    intersection = [line for line in lines_updated if line in lines_original]
    url = "http://bari.opendata.planetek.it/OrariBus/v2.1/OpenDataService.svc/REST/OrariPalina/%s/teorico" %stop_id
    result = urlfetch.fetch(url=url, method=urlfetch.GET)

    #estraggo l'elenco degli orari relativi alla fermata che mi interessa
    previsions = json.loads(result.content)["PrevisioniLinee"]
    previsions = filter(lambda prevision: (prevision["Direzione"] ==line["Direzione"] for line in intersection), previsions)
    previsions = filter(lambda prevision: (prevision["IdLinea"] ==line["IdLinea"] for line in intersection), previsions)

    notification_result = [dict(line=prevision["IdLinea"], time=get_time_by_previon(prevision), stop_address=stop_address, distance_mt = distance_mt) for prevision in previsions]
    return notification_result
Esempio n. 3
0
def users():
    selectuser = request.form.get('selectuser', '')
    userlist = models.get_user(selectuser)
    if session.get('user') is None:
           return redirect('/')
    username = session.get('user')
    return render_template('user_list.html',users=userlist,username=username);
Esempio n. 4
0
def handle_scenarios(request, res, case):
    req = request.json

    if request.headers.get('Authorization'):

        token = request.headers.get('Authorization').replace('Bearer ', '')
        if token:
            user_email = get_user_email(token)
            if user_email:
                user = models.get_user(user_email)
                if user and user.device_address and user.device_token:
                    res['response']['end_session'] = True
                    if case == 0:  # test scenario
                        res['response'][
                            'text'] = 'Надеюсь, ты услышишь мое тайное послание через пару секунд.'
                    else:
                        res['response']['text'] = '.'
                    taskqueue.add(url='/alice/task?u=%s&c=%s' %
                                  (user_email, case),
                                  countdown=3,
                                  method='GET')
                else:
                    res['response'][
                        'text'] = 'Похоже, ты не завершил настройки на сайте. Сделай это и возвращайся!'

            else:
                res['response'][
                    'text'] = 'Похоже, ты еще не сделал настройки на сайте. Либо использовал разные аккаунты здесь и на сайте. Проверь все и возвращайся.'
        else:
            res['response'][
                'text'] = 'Сначала необходимо пройти авторизацию, скажи "Авторизация" для начала.'

        return
    else:
        request_auth(req, res)
Esempio n. 5
0
def users():
    selectuser = request.form.get('selectuser', '')
    userlist = models.get_user(selectuser)
    if session.get('user') is None:
        return redirect('/')
    username = session.get('user')
    return render_template('user_list.html', users=userlist, username=username)
Esempio n. 6
0
def add() :
    form = SongForm(request.form)
    if form.validate():
        songData = form.data['song'].split(" - ")
        notTitle = songData[1].split(" (")
        artist = notTitle[0]
        album = notTitle[1].split(")")[0]
        song = models.get_song(songData[0], artist, album)
        user = models.get_user(current_user.get_id())
        print song.id
        print song.artist
        print song.album
        print song.pi_owner
        if song != None and user != None:
            uname = current_user.get_id()
            all_songs = g.db.query(Song).all()
            your_songs = g.db.query(Queue).filter_by(owner=uname).all()
            queue = g.db.query(Queue).all()
            nextSong = Queue(id=song.id, album = song.album, artist = song.artist, title = song.title, pi_owner = song.pi_owner, owner=user.name)
            qsong = models.get_qsong(songData[0], artist, album)
            if qsong == None:
                g.db.add(nextSong)
                g.db.flush()
                return redirect(url_for("home"))
                #render_template('home.html', your_songs=your_songs, uname=uname, songs=all_songs)
            else:
                return render_template('home.html', your_songs=your_songs, uname=uname, songs=all_songs, error="You've already added that song to the list!", queue=queue)
                #return render_template("home.html", ) 
            #return redirect(url_for("home"))
        return render_template("home.html", error="Song not in available list.")
    return render_template("home.html", error="Uhoh. Looks like you forgot to enter a song!")
Esempio n. 7
0
def users():
	if session.get('user') is None:
		return redirect('/')

	users = models.get_user()
	#print users
	return render_template('user.html',users=users)
 def post(self):
     shot_id = self.get_argument('shot_id')
     username = self.get_argument('username')
     shot_upheld = self.get_argument('shot_upheld')
     claim = self.get_argument('claim', '')
     
     try:
         resolving_user = get_user(username=username)
         shot = get_shot(shot_id)
         game = get_game(shot.game_id)
         session = Session()
         
         mission = get_mission(game_id=game.id, assassin_id=shot.assassin_id, target_id=shot.target_id, completed_timestamp=None)
         
         if shot_upheld == 'True':
             if shot.target_id == resolving_user.id or resolving_user in game.game_masters:
                 shot.kill_upheld = True
                 game.mission_completed(mission, shot)
                 response_dict = get_response_dict(True)
         else:
             if shot.target_id == resolving_user.id:
                 dispute = Dispute(game.id, shot_id, claim)
                 session.add(dispute)
                 session.flush()
                 session.commit()
                 response_dict = get_response_dict(True)
             elif resolving_user in game.game_masters:
                 shot.kill_upheld = False
                 response_dict = get_response_dict(True)
     except Exception as e:
         session.rollback()
         response_dict = get_response_dict(False, e.message)
     finally:
         Session.remove()
         self.finish(simplejson.dumps(response_dict))
Esempio n. 9
0
 def post(self):
   user = models.get_user()
   if user:
       loc = simplejson.loads(self.request.get('payload'))
       path = loc['origin'] + loc['pathname']
       pages = models.Page.gql("WHERE owner = :1 AND url = :2 ", user.bucket_set[0], path)
       
       if pages.count() > 0:
           page = pages[0]
           pagekey = str(page.key())
           stickies=[]
           
           for sticky in page.sticky_set:
              if sticky.is_deleted == False:
                  json = {}
                  json['pagekey'] = pagekey
                  content = simplejson.loads(sticky.content)
                  content['key'] = str(sticky.key())
                  json['content'] = simplejson.dumps(content)
              
                  #json['updated'] = sticky.updated 
                  stickies.append(json)
       
           self.response.out.write(simplejson.dumps(stickies))
   else:
       self.response.out.write(simplejson.dumps(create_login_logout_json(self.request)))
Esempio n. 10
0
def post_edit_profile():
    user = get_user(request)
    if user:

        # Username shouldn't already exist
        username = request.forms.get('username')
        try:
            existing_user = User.get(username=username)
            if existing_user and existing_user != user:
                the_html = open('edit_profile.html').read()
                response.flash("That username is taken!")
                return template(the_html, user=user, request=request)
        except User.DoesNotExist:
            pass

        # Email should look vaguely legitimate
        # TODO: security thing - should we enforce confirmation
        # w/ the old email address?
        email = request.forms.get('email')
        if '@' not in email and '.' not in email.split('@')[1]:
            the_html = open('edit_profile.html').read()
            response.flash("That email is invalid!")
            return template(the_html, user=user, request=request)

        user.username = request.forms.get('username')
        user.first_name = request.forms.get('first_name')
        user.last_name = request.forms.get('last_name')
        user.email = request.forms.get('email')
        user.save()

        response.flash("Your profile has been updated")
    redirect('/')
Esempio n. 11
0
def login():
    if request.method == 'POST':
        user = request.form['user_name']
        password_input = request.form['pass_word']
        if user and password_input is not None:

            if get_user(user):
                test_user_data = get_test_user(user)
                user_models = User_login(test_user_data.id,
                                         test_user_data.username,
                                         test_user_data.email,
                                         test_user_data.password)
                password = user_models.check_password(password_input)
                if password:
                    login_user(test_user_data)
                    # session['username'] = user_models.get_id()
                    flash("login successfull", "success")
                    return redirect(url_for('get_rooms'))
                else:
                    flash("password is incorrect", "danger")
            else:
                flash("Invalid Credintials", "danger")
        else:
            flash("username and password not met", "danger")

    return render_template('login.html')
    def post(self):
        username = self.get_argument('username')
        game_id = self.get_argument('game_id')
        dispute_id = self.get_argument('dispute_id')
        shot_upheld = self.get_argument('dispute_upheld')
        gm_decision_reason = self.get_argument('gm_decision_reason')

        session = Session()
        try:
            dispute = session.query(Dispute).filter_by(id=dispute_id).one()
            shot = session.query(Shot).filter_by(id=dispute.shot_id).one()
            resolving_user = get_user(username=username)
            game = get_game(game_id)
            mission = get_mission(game_id=game_id, assassin_id=shot.assassin_id, target_id=shot.target_id, completed_timestamp=None)
            if resolving_user in game.game_masters:
                if shot_upheld == 'True':
                    game.mission_completed(mission)
                    dispute.shot_upheld = True
                else:
                    dispute.shot_upheld = False
                    target_usergame = get_usergame(shot.target_id, game.id)
                    if target_usergame.alive == None:
                        target_usergame.alive = True
                        session.add(target_usergame)
                dispute.gm_decision_reason = gm_decision_reason
                session.add(dispute)
                session.flush()
                session.commit()
                response_dict = get_response_dict(True)
                
            else:
                response_dict = get_response_dict(False, 'Only the game master can resolve a dispute')
        except Exception, e:
            session.rollback()
            response_dict = get_response_dict(False, e.message)
    def post(self):
        game_id = self.get_argument('game_id')
        game_password = self.get_argument('game_password')
        username = self.get_argument('username')

        session = Session()
        try:
            user = get_user(username)
            game = get_game(game_id=game_id, game_password=game_password)
            try:
                usergame = get_usergame(user.id, game.id)
                if usergame is not None:
                    response_dict = get_response_dict(True)
            except NoResultFound:
                if not game.started:
                    game.add_user(user)
                    response_dict = get_response_dict(True)
                else:
                    response_dict = get_response_dict(False, 'Game has started; you cannot join.')
                    
        except Exception as e:
            session.rollback()
            response_dict = get_response_dict(False, e.message)
        finally:
            Session.remove()
            self.finish(simplejson.dumps(response_dict))
Esempio n. 14
0
def perform_scenario():

    user_email = request.args.get('u')
    case = request.args.get('c')

    if user_email and case:
        logging.info('Performing task for user %s' % user_email)
        user = models.get_user(user_email)
        case = int(case)
        if case == 0:  # test scenario
            send_text(
                user.device_address, user.device_token,
                ['Повтори за мной Супер! Похоже, что всё работает как надо!'])
        elif case == 1 or case == 2:
            if case == 1:
                scenario = user.scenario1
            elif case == 2:
                scenario = user.scenario2
            if scenario[0]:
                commands = json.loads(scenario)
                if commands:
                    send_text(user.device_address, user.device_token, commands)
                else:
                    send_text(
                        user.device_address, user.device_token,
                        ['Повтори за мной Не удалось прочитать сценарий.'])
            else:
                send_text(user.device_address, user.device_token, [
                    'Повтори за мной Отсутствуют команды в данном сценарии. Задайте их на сайте.'
                ])
Esempio n. 15
0
def confirm():
    """Confirm an account (via clicking a link in email)."""
    token = request.query.token
    user = get_user(request, token)
    if user:
        set_user_token(user)
        redirect('/set_password')
    return "<p>No user with that token</p>"
Esempio n. 16
0
def insert_user():
    user = serializers.users_from_web(**request.json)
    if valida_user(**user):
        id_usuario = models.insert_user(**user)
        inserted_user = models.get_user(id_usuario)
        return jsonify(serializers.users_from_db(inserted_user))
    else:
        return jsonify({"erro": "Usuário inválido"})
Esempio n. 17
0
def update_users(id):
    user = serializers.users_from_web(**request.json)
    if valida_user(**user):
        models.update_user(id, **user)
        inserted_user = models.get_user(id)
        return jsonify(serializers.users_from_db(inserted_user))
    else:
        return jsonify({"erro": "Usuário inválido"})
Esempio n. 18
0
def get_five_user():
  result = None
  user = users.get_current_user()
  if user: 
    result = models.get_user(user.email())
    # if we have a logged-in user but no FiveUser object, we will create one.
    if not result:
      result = models.save_user(user.email())
  return result
Esempio n. 19
0
    def get(self, stuID):
        uid = get_uid(stuID)

        # Update number of selected course of a user
        user = models.get_user(uid)
        models.set_user_select_course(uid, get_num_of_selected_courses(uid))

        info = user_info_by_uid(uid)
        return info, 200
Esempio n. 20
0
def index():
    user = get_user(request)
    the_html = open('the.html').read()
    last_msgs = Message.select().order_by(-Message.id)[:10]
    return template(the_html,
                    messages=reversed(last_msgs),
                    user=user,
                    request=request,
                    config=config)
Esempio n. 21
0
def view_user():
    if not session.get('user'): return redirect('/')
    u_valid = request.args.get('u_valid')
    result = models.get_user()
    hobbys = {'swim': '游泳', 'climb': '爬山', 'basketball': '篮球'}
    return render_template('users.html',
                           users=result,
                           u_valid=u_valid,
                           hobbys=hobbys)
Esempio n. 22
0
  def get(self, userid):
    user = models.get_user(long(userid))
    if user is None or not hasattr(user, 'avatar') or user.avatar is None:
      self.redirect('/images/default_avatar.png')
      return

    else:
      self.response.headers['Content-Type'] = "image/png"
      self.response.out.write(user.avatar)
      return
Esempio n. 23
0
def event(event_id):
    e = Event.query.filter_by(id=event_id).first()
    if not e:
        return json_out({"status_code": 2})  # event doesn't exist

    if request.method == "GET":
        result = {
            "status_code": 0,
            "id": e.id,
            "name": e.name,
            "start_time": "" if not e.start_time else unix_time(e.start_time),
            "end_time": "" if not e.end_time else unix_time(e.end_time),
            "is_private": e.is_private,
            "manager_id": e.manager_id,
            "task_list": map(lambda t: t.id, e.tasks),
            "user_list": map(lambda u: u.id, e.volunteers),
            "description": e.description
        }
        return json_out(result)

    elif request.method == "PUT":
        for key in request.form:
            if key in e.__dict__:
                if key == "start_time":
                    start_time = parser.parse(request.form['start_time'])
                    setattr(e, "start_time", start_time)
                elif key == "end_time":
                    end_time = parser.parse(request.form['end_time'])
                    setattr(e, "end_time", end_time)
                elif key == "is_private":
                    setattr(e, "is_private", True)
                elif key == "name" or key == "description":
                    setattr(e, key, request.form[key])
            elif key == "user_list":
                try:
                    L = json.loads(request.form[key])
                    assert (type(L) == list)
                except:
                    return json_out_err("Not a valid " + key)
                volunteers = [get_user(id=i) for i in L]
                if None in volunteers:
                    idd = L[volunteers.index(None)]
                    return json_out_err("Not a valid user_id: %d" % idd)
                e.volunteers = volunteers
            else:
                return json_out_err("Not a valid field: " + key)
        db.session.commit()
        return json_out({"status_code": 0})

    elif request.method == "DELETE":
        if e.manager_id != current_user.id:
            return json_out({"status_code": 1})
        db.session.delete(e)
        db.session.commit()
        return json_out({"status_code": 0})
    def post(self):
        username = self.get_argument('username')
        game_id = self.get_argument('game_id')
        shot_picture = None
        target_username = self.get_argument('target_username')
        mission_id = self.get_argument('mission_id', None)
        session = Session()
        try:
            target_user = get_user(username=target_username)
            assassin_user = get_user(username=username)
            game = get_game(game_id)
            mission = get_mission(game_id=game_id, assassin_username=username, target_id=target_user.id)
            
            picture_binary = self.request.files['shot_picture'][0]['body']
            shot_picture_url = imgur.upload(file_body=picture_binary)

            player_shooting_target = Shot(assassin_id=assassin_user.id, \
                                        target_id=target_user.id, \
                                        game_id=game_id, \
                                        shot_picture=shot_picture_url)
            session.add(player_shooting_target)
            session.flush()
            session.commit()
            target_usergame = get_usergame(user_id=target_user.id, game_id=game_id)
            if player_shooting_target.is_valid():
                target_usergame.alive = None  # mark them as shot
                target_usergame.pending_shot = player_shooting_target.id
                session.add(target_usergame)
                session.flush()
                session.commit()
                response_dict = get_response_dict(True)
            else:
                if target_usergame.alive is None:
                    response_dict = get_response_dict(False, "Shot invalid.  Your target was previously shot, and the kill needs to be confirmed by him/her or the game master")
                else:
                    response_dict = get_response_dict(False, "Shot invalid.  If this was your target in this game, maybe they had a body double or you need to wait?")
        except Exception as e:
            session.rollback()
            response_dict = get_response_dict(False, e.message)
        finally:
            Session.remove()
            self.finish(simplejson.dumps(response_dict))
Esempio n. 25
0
def admin_internal():
    if request.method == "POST":
        new_admins = [
            get_user(id=int(n)) for n in request.form.getlist('new-admins')
        ]
        new_losers = [
            get_user(id=int(n)) for n in request.form.getlist('new-losers')
        ]
        for u in new_admins:
            u.permissions = request.form["permissions"]
        for u in new_losers:
            u.permissions = ""

        db.session.commit()
        flash("Permissions updated.")
        return redirect(url_for("index"))

    return render_template('admin.html',
                           user=current_user,
                           user_list=User.query.all())
Esempio n. 26
0
  def get(self):
    requires_user(self)

    param = self.request.get('users');
    if not param or re.match('(\d+-)*\d+$', param) is None:
      self.redirect('/')
      return

    # construct google charts url
    userids = re.split('-', param)
    userids = userids[:6] # keep only forst 6 entries
    min_score = 10000
    max_score = 0
    oldest = 0
    charts = []
    usernames = []
    for userid in userids:
      usernames.append(str(models.get_user(userid).user))
      scores = models.get_scores(int(userid))
      if not scores is None:
        x = []
        y = []
        for score in scores:
          x.append((date.today() - score.date).days)
          y.append(round(score.score))
          min_score = min(round(score.score), min_score)
          max_score = max(round(score.score), max_score)
          oldest = max((date.today() - score.date).days, oldest)
        if x.count(0) == 0:
          x.append(0)
          y.append(y[-1])
        charts.append([ x, y ])

    def adapt_date(d): return str((oldest - d) * 100 / oldest)
    def adapt_score(s): return str((s - min_score + 10) * 100 / (max_score - min_score + 10))
    def adapt_chart(l): return [ map(adapt_date, l[0]), map(adapt_score, l[1]) ]
    charts = map(adapt_chart, charts)

    chart_url = 'http://chart.apis.google.com/chart?chs=600x250&cht=lxy'+\
                '&chco=003DF5,F5003D,3DF500,F5F500,FF70B8,CC6600&chd=t:'
    chart_data = []
    for chart in charts:
      chart_data.append(','.join(chart[0]) + '|' + ','.join(chart[1]))
    chart_url += '|'.join(chart_data) + '&chdl=' + '|'.join(usernames)
      
    template_file = os.path.join(os.path.dirname(__file__), 'templates/compare.html')
    template_values = {
      'greeting': get_greeting(),
      'is_admin': is_admin(),
      'is_registered': is_registered(),
      'chart_url': chart_url
    }

    self.response.out.write(Template(filename=template_file,lookup=mylookup).render_unicode(**template_values))
Esempio n. 27
0
async def resend_photo(call):
    photo_url = call.data.replace('send', '')

    current_user = models.get_user(call.message.chat.id)
    print(models.get_all_users)
    for i in models.get_all_users():
        if not i.chat_id == current_user.chat_id:
            await bot.send_photo(i.chat_id, photo=photo_url)

    await bot.send_message(current_user.chat_id, 'Фотография отправлена'
                                                 ' всем пользователям!')
Esempio n. 28
0
def handleLogin():
    if request.form.get("username") and request.form.get("password"):
        username = request.form["username"]
        password = request.form["password"]
        result = models.get_user(username, password)
        if result:
            return jsonify({"message": "success", "permission": result[0][0]})
        else:
            return jsonify(
                {"message": "Login fail, Username or password is incorrect"})
    return jsonify({"message": "error"})
Esempio n. 29
0
File: app.py Progetto: MBloom/OneDir
def login():
    form = LoginForm(request.form)
    if form.validate():
        # since the form isn't bad, we check for valid user
        user = models.get_user(form.data['username'])
        if user != None and User.check_password(form.data['username'], form.data['password']):
            login_user(user)
            return redirect(request.args.get("next") or url_for("home"))
        else:
            return render_template("login.html", form=form, message="Username/password do not match.")
    return render_template("login.html", form=form, message=None)
Esempio n. 30
0
def sign_up():
    username = request.form['email']
    password = request.form['password']
    if models.get_user(username) == None:
        user = models.Users(username,utils.encrypt(password))
        db.session.add(user)
        db.session.commit()
        session['logged_in'] = True
        session['username'] = username
        return json.dumps({'status':'ok'})
    #return redirect(url_for('show_news', fecha_raw= utils.get_today()))
    return json.dumps({'status':'error','error':'Usuario ya existe'})
Esempio n. 31
0
def get_plot(username: str):
    """Main entrance to plotting - get plot filename from username."""
    username = username.lower()
    # Check if already in database
    user = get_user(username)
    if user is None: # not found on GitHub
        return None
    if user.plot_filename:
        return user.plot_filename
    else:
        plot_filename = plot_activity(username=username)
    return plot_filename
Esempio n. 32
0
def modify_user():
    username = request.args.get('username', '')
    user = models.get_user(username)
    error = ''
    username = ''
    password = ''
    if user is None:
        error = 'username is not exists'
    else:
        username = user['name']
        password = user['password']
    return render_template('user_modify.html',username=username,password=password,error=error)
Esempio n. 33
0
def post_set_password():
    user = get_user(request)
    if user:
        password = request.forms.get('password')
        password_check = request.forms.get('password_check')
        if password != password_check:
            the_html = open('password_change.html').read()
            response.flash("Those passwords don't match!")
            return template(the_html, user=user, request=request)
        set_user_password(user, password)
        response.flash("Your password has been changed")
        redirect('/')
Esempio n. 34
0
  def get(self):
    param = self.request.get('users');
    if not param or re.match('(\d+-)*\d+$', param) is None:
      self.redirect('/')
      return

    # construct google charts url
    userids = re.split('-', param)
    userids = userids[:MAX_CHART_ENTRIES] # keep only first n entries
    min_score = 10000
    max_score = 0
    oldest = 0
    charts = []
    usernames = []
    for userid in userids:
      usernames.append(unicode(models.get_user(userid).nickname))
      scores = models.get_scores(int(userid))
      if not scores is None:
        x = []
        y = []
        for score in scores:
          x.append((date.today() - score.date).days)
          y.append(round(score.score))
          min_score = min(round(score.score), min_score)
          max_score = max(round(score.score), max_score)
          oldest = max((date.today() - score.date).days, oldest)
        if x.count(0) == 0:
          x.append(0)
          y.append(y[-1])
        charts.append([ x, y ])

    def adapt_date(d): return unicode((oldest - d) * 100 / oldest)
    def adapt_score(s): return unicode((s - min_score + 10) * 100 / (max_score - min_score + 10))
    def adapt_chart(l): return [ map(adapt_date, l[0]), map(adapt_score, l[1]) ]
    charts = map(adapt_chart, charts)

    chart_url = 'http://chart.apis.google.com/chart?chs=600x250&cht=lxy&chco='+\
                ','.join(COLORS[:len(userids)]) + '&chd=t:'
    chart_data = []
    for chart in charts:
      chart_data.append(','.join(chart[0]) + '|' + ','.join(chart[1]))
    chart_url += '|'.join(chart_data) + '&chdl=' + '|'.join(usernames)
      
    template_file = os.path.join(os.path.dirname(__file__), 'templates/compare.html')
    template_values = {
      'greeting': get_greeting(),
      'is_admin': is_admin(),
      'is_registered': is_registered(),
      'chart_url': chart_url
    }

    self.response.out.write(Template(filename=template_file,lookup=mylookup).render_unicode(**template_values))
Esempio n. 35
0
def task(task_id):
    t = Task.query.filter_by(id=task_id).first()
    if not t:
        return json_out({"status_code": 2})  # event doesn't exist

    if request.method == "GET":
        result = {
            "status_code": 0,
            "id": t.id,
            "name": t.name,
            "start_time": "" if not t.start_time else unix_time(t.start_time),
            "end_time": "" if not t.end_time else unix_time(t.end_time),
            "location": t.location,
            "description": t.description,
            "event_id": t.event_id,
            "user_list": map(lambda u: u.id, t.volunteers)
        }
        return json_out(result)

    elif request.method == "PUT":
        for key in request.form:
            if key in t.__dict__:
                if key == "start_time":
                    start_time = parser.parse(request.form['start_time'])
                    setattr(t, "start_time", start_time)
                elif key == "end_time":
                    end_time = parser.parse(request.form['end_time'])
                    setattr(t, "end_time", end_time)
                elif key == "name" or key == "description" or key == "location":
                    setattr(t, key, request.form[key])
            elif key == "user_list":
                try:
                    L = json.loads(request.form[key])
                    assert (type(L) == list)
                except:
                    return json_out_err("Not a valid " + key)
                volunteers = [get_user(id=i) for i in L]
                if None in volunteers:
                    idd = L[volunteers.index(None)]
                    return json_out_err("Not a valid user_id: %d" % idd)
                t.volunteers = volunteers
            else:
                return json_out_err("Not a valid field: " + key)
        db.session.commit()
        return json_out({"status_code": 0})

    elif request.method == "DELETE":
        if t.event and t.event.manager_id != current_user.id:
            return json_out({"status_code": 1})
        db.session.delete(t)
        db.session.commit()
        return json_out({"status_code": 0})
Esempio n. 36
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = get_user(form.email.data)
        if user is not None and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            next_page = request.args.get('next')
            if not next_page or url_parse(next_page).netloc != '':
                next_page = url_for('index')
            return redirect(next_page)
    return render_template('login_form.html', form=form)
Esempio n. 37
0
def update_status(username):
    # Get user from db model
    user = get_user(username)

    # Parse request body as JSON
    json_in = request.json

    # Copy fields from JSON object to model
    user.from_json(json_in)

    # Save to database
    user.save()
    db_session.commit()
Esempio n. 38
0
async def get_user(user_id: str,
                   current_user: User = Depends(get_current_user)):
    if not current_user.superuser and user_id != current_user.user_id:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail='Insufficient rights to resource')
    if user_id != current_user.user_id:
        user = models.get_user(user_id)
    else:
        user = current_user
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail='User not found')
    return user
Esempio n. 39
0
async def handler(websocket, path):
    """Handler for websockets.
           - Receive + auth incoming msgs
           - Post them out to everyone else."""
    global connected
    
    cookie = cookies.SimpleCookie()
    cookie.load(websocket.request_headers['Cookie'])
    user = get_user(request=None, token=cookie['token'].value)
    if not user:
        websocket.close()
        return
    websocket.user = user
    
    # When someone connects, we save it so that we can spam^Wmessage
    # them later on
    connected.add(websocket)
        
    # DEBUG
    print(("-" * 42))
    print(("REQUEST:", websocket.raw_request_headers))
    print(("RESPONSE:", websocket.raw_response_headers))
    #print("DIR:", dir(websocket))
    print(("TOKEN:", cookie['token'].value))
    print(("USER:"******"-" * 42 + "\n"))
    while True:
        listener_task = asyncio.ensure_future(websocket.recv())
        
        # This needs to be a coroutine that finds/"produces" messages to 
        # send back to the web client, but it's not clear how this would work
        #producer_task = asyncio.ensure_future(producer())
        
        # Maybe we don't need a producer future/task?
        # try using the .send() function on every other connected websocket
        done, pending = await asyncio.wait(
            [listener_task],
            return_when=asyncio.FIRST_COMPLETED)
        
        # We haz a message - process it! :)
        message = listener_task.result()
        print(("MESSAGE:", message))
        
        message = url.make_urls(message)
        
        # insert message into db
        msg = Message(content=message, user=user)
        msg.save()
        
        await send_messages(msg, websocket)
Esempio n. 40
0
File: app.py Progetto: MBloom/OneDir
def change_pwd():
    form = AdminPwdChange(request.form)
    if form.validate():
        user = models.get_user(form.data['username'])
        if user == None:
            message = "No such user exists"
            return render_template("change_pwd.html", form=form, message=message)
        elif form.data['new_pwd'] != form.data['auth_pwd']:
            message = "Passwords do not match."
            return render_template("change_pwd.html", form=form, message=message)
        else:
            user.password = form.data['new_pwd']
            return redirect(url_for("admin"))
    return render_template("change_pwd.html", form=form, message=None)
 def get(self):
     username = self.get_argument('username')
     logger = logging.getLogger('ViewMission')
     session = Session()
     try:
         user = get_user(username=username)
         missions = session.query(Mission).filter_by(assassin_id=user.id, completed_timestamp=None)
         response = [x.get_api_response_dict() for x in missions]
     except Exception as e:
         response = get_response_dict(False, e.message)
         session.rollback()
     finally:
         Session.remove()
         self.finish(simplejson.dumps(response))
Esempio n. 42
0
def make_challenge(request, username):
    user = get_user(username)
    done = False
    while not done:
        try:
            challenge = Challenge(destination=user)
            challenge.save()
            done = True
        except IntegrityError:
            pass
    # occasional cleanup
    if challenge.code[1] == "0":
        Challenge.objects.filter(valid_until__lt=datetime.now()).delete()
    return HttpResponse(challenge.code)
Esempio n. 43
0
  def post(self):
    if not requires_registered(self):
      return

    score1 = long(self.request.get('score1', 0))
    score2 = long(self.request.get('score2', 0))
    opponent = long(self.request.get('player2', 0))

    if (score1 != 3 and score2 != 3) or (score1 == 3 and score2 == 3):
      self.redirect('/match/simulate')
      return

    me = models.get_user_(users.get_current_user())
    userscore1 = me.score
    userscore2 = models.get_user(opponent).score

    if score1 > score2:
      [ userscore1, userscore2 ] = elo.compute_score(userscore1, userscore2, abs(score1 - score2))
    else:
      [ userscore2, userscore1 ] = elo.compute_score(userscore2, userscore1, abs(score1 - score2))

    template_file = os.path.join(os.path.dirname(__file__), 'templates/simulate.html')
    template_values = {
      'greeting': get_greeting(),
      'is_admin': is_admin(),
      'is_registered': is_registered(),
      'me': me,
      'registered_users': models.get_possible_opponents(),
      'score1': score1,
      'score2': score2,
      'opponent': opponent,
      'opponent_nickname': models.get_user(opponent).nickname,
      'userscore1': userscore1,
      'userscore2': userscore2
    }
    self.response.out.write(Template(filename=template_file,lookup=mylookup).render_unicode(**template_values))
Esempio n. 44
0
 def post(self):
     errors = []
     username = self.request.get('username');logging.error(username)
     password = self.request.get('password');logging.error(password)
     redirect = self.request.get('redirect');logging.error(redirect)
     if (username and password):
         username = utils.clean_input(username)
         user = models.get_user(username, password)
         if user:
             self.set_user(user)
             self.redirect((str(redirect) or '/blog/posts'))
         errors.append('Login Error: incorrect username or password.')
     if not username: errors.append('Username is required.')
     if not password: errors.append('Password is required.')
     self.render_template('login.html', {'errors': errors, 'redirect': redirect})
Esempio n. 45
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user_id = hash256_login(username, password)
        returned_user = get_user(user_id)

        if returned_user:
            user_info = {
                'user_id'       : returned_user[0][0],
                'username'      : returned_user[0][1],
                'date_created'  : returned_user[0][2],
                'num_sessions'  : returned_user[0][3]
            }

    return render_template('register.html')
Esempio n. 46
0
 def post(self):
     logger = logging.getLogger("BuyPowerup")
     session = Session()
     try:
         username = self.get_argument('username')
         item_id = self.get_argument('item_id')
         game_id = self.get_argument('game_id')
     
         user = get_user(username)
         purchase_powerup(user.id, game_id, item_id)
         session.commit()
         result_dict = get_response_dict(True)
     except Exception, e:
         logger.exception(e)
         session.rollback()
         result_dict = get_response_dict(False, e.message)
Esempio n. 47
0
  def get(self, userid):
    opponent = models.get_user(userid)

    if opponent is None:
      error404(self)
      return

    template_file = os.path.join(os.path.dirname(__file__), 'templates/user.html')
    template_values = {
      'greeting': get_greeting(),
      'is_admin': is_admin(),
      'is_registered': is_registered(),
      'user': opponent,
      'matches': models.get_user_matches(opponent.user)
    }

    self.response.out.write(Template(filename=template_file,lookup=mylookup).render_unicode(**template_values))
Esempio n. 48
0
  def post(self):
    if not requires_registered(self):
      return

    match_id = models.create_new_match(users.get_current_user(), self.request)
    memcache.delete_multi([ "ranks", "matches_home_admin", "matches_home" ])

    if match_id is None:
      self.redirect('/') # TODO error message
      return

    models.update_scores(match_id)

    body = "%s %s - %s %s" % (models.get_user_(users.get_current_user()).nickname, self.request.get('score1'),\
                              self.request.get('score2'), models.get_user(long(self.request.get('player2'))).nickname)
    xmpp.send_message(models.get_jids(), body, APP_URL + "@appspot.com", xmpp.MESSAGE_TYPE_CHAT)
    
    self.redirect('/')
Esempio n. 49
0
  def post(self):
    if not requires_registered(self):
      return

    mail_to_key = long(self.request.get('mail_to', 0));
    body = unicode(self.request.get('message', ''));
    subject = unicode(self.request.get('subject', ''));

    recipient = models.get_user(mail_to_key)

    sender_address = users.get_current_user().email()
    
    if recipient is not None:
      mail_to = recipient.nickname + ' <' + recipient.user.email() + '>'
      mail.send_mail(sender_address, mail_to, subject, body)

    self.redirect('/')
    return
Esempio n. 50
0
File: app.py Progetto: MBloom/OneDir
def remove_user():
    all_users = g.db.query(User).all()
    form = AccountRemoval(request.form)
    if form.validate():
        user_toRemove = models.get_user(form.data['username'])
        if user_toRemove == None:
            message = "User does not exist."
            return render_template("remove_user.html", all_users=all_users, form=form, message=message)
        else:
            map(lambda f: g.db.delete(f), user_toRemove.files)
            g.db.delete(user_toRemove)
            return redirect(url_for("admin"))
    # admin authentication
    admins = g.db.query(User).filter_by(userClass="admin").all()
    if current_user in admins:
        return render_template("remove_user.html", all_users=all_users, form=form, message=None)
    else:
        abort(404)
Esempio n. 51
0
File: api.py Progetto: MBloom/OneDir
def move_dir(username):
    """This method requires to=<path>&from=<path> as url params"""
    to_path = request.args["to"]
    from_path = request.args["from"]

    from_dir = get_dir(username, from_path)
    to_dir   = get_dir(username, to_path)
    user     = get_user(username)

    if not to_dir is None:
        return "", status.HTTP_409_CONFLICT

    if None in [from_dir, user]:
        print from_dir, to_dir, user
        return "", status.HTTP_405_METHOD_NOT_ALLOWED

    from_dir.path = to_path
    g.db.add(from_dir) 
    return {}, status.HTTP_202_ACCEPTED
Esempio n. 52
0
def create_user():
    form = AccountForm(request.form)
    if form.validate():
        user = models.get_user(form.data['username'])
        if user != None:
            message = "User already exists. Please choose another username."
            return render_template("create.html", form=form, message=message)
        elif form.data['password'] != form.data['auth_pass']:
            message = "Passwords do not match."
            return render_template("create.html", form=form, message=message)
        else:
            new_user = User(name=form.data['username'],
                            password=form.data['password'],
                            role="user")
            g.db.add(new_user)
            login_user(new_user)
            return redirect(url_for("home"))
    print form.data
    return render_template("create.html", form=form, message=None)
Esempio n. 53
0
 def get(self):
     logger = logging.getLogger('Inventory')
     username = self.get_argument('username')
     game_id = self.get_argument('game_id')      
    
     try:
         session = Session()
      
         user = get_user(username)
         pwrlist = list_powerup_for_usergame(user, game_id)
         purchased_json_array = []
         for powerup in pwrlist:
             purchased_json_array.append(powerup.get_api_response_dict())
         return_obj = purchased_json_array
         
     except Exception, e:
         logger.exception(e)
         session.rollback()
         return_obj = []
Esempio n. 54
0
 def post(self):
     logger = logging.getLogger('DisablePowerup')
     session = Session()
     try:
         game_id = self.get_argument('game_id')
         username = self.get_argument('username')
         power_id = self.get_argument('powerup_id')
         user = get_user(username)
         ug = get_usergame(user.id, game_id)
         
         if(ug.is_game_master):
             game = get_game(game_id)
             game.disable_powerup(user.id, power_id)
             session.commit()
             result_dict = get_response_dict(True)
         else:
             raise Exception("You are not a Game Master for the given game_id")
         
     except Exception, e:
         logger.exception(e)
         session.rollback()
         result_dict = get_response_dict(False, e.message)
Esempio n. 55
0
File: api.py Progetto: MBloom/OneDir
def move_file(username):
    """Requires to=<> and from=<> parameters"""
    to_fpath   = request.args["to"]
    from_fpath = request.args["from"]
    from_path, old_name = os.path.split(from_fpath)
    to_path, new_name = os.path.split(to_fpath)

    print "yes"
    from_dir = get_dir(username, from_path)
    to_dir   = get_dir(username, to_path)
    user     = get_user(username)

    if None in [from_dir, to_dir, user]:
        print from_dir, to_dir, user
        return "", status.HTTP_405_METHOD_NOT_ALLOWED

    file = g.db.query(File).filter_by(owner=user.name,
                                      dir=from_dir.inode,
                                      name=old_name).first()
    file.dir = to_dir.inode
    file.name = new_name
    g.db.add(file)
    print "yes"
    return {}, status.HTTP_202_ACCEPTED
 def post(self):
     friendly_name = self.get_argument('friendly_name')
     game_master_username = self.get_argument('game_master_username')
     try:
         base_money = int(self.get_argument('base_money'))
     except:
         base_money = game_constants.DEFAULT_STARTING_MONEY
     password = self.get_argument('game_password')
     session = Session()
     try:
         game_master = get_user(game_master_username)
         game = Game(title=friendly_name, password=password, starting_money=base_money)
         session.add(game)
         session.flush()
         game.add_game_master(game_master)
         result_dict = get_response_dict(True)
         session.commit()
         result_dict['game_id'] = game.id
     except Exception as e:
         session.rollback()
         result_dict = get_response_dict(False, e.message)
     finally:
         Session.remove()
         self.finish(simplejson.dumps(result_dict))
Esempio n. 57
0
def users():
    selectuser = request.form.get('query', '')
    userlist = models.get_user(selectuser)
    username = session.get('user')
    return render_template('user.html',users=userlist,username=username);
Esempio n. 58
0
def update_user():
    params = request.args if request.method == 'GET' else request.form
    username = params.get('username', '')
    userinfo=models.get_user(username)
    # 返回templates目录下的updata.html模板中的内容
    return render_template('updata.html',userinfo=userinfo)