예제 #1
0
def echo_endpoint():
    try:
        #print(type(request.data))
        #print(request.data)
        image_bytes = construct_image(raw_bytes=request.data)
        token = get_token(request)
        users.get_user(token=token)
    except classes.UserAuthenticationError as bad_token_error:
        return error_response_unauthorized(message=str(bad_token_error))
    except classes.UserNotFoundError:
        return error_response_unauthorized(
            message='No user associated with your token.')
    except classes.ImageNotFoundError:
        return error_response_bad_request(
            message='Please include an image in your request body.')

    try:
        request_id = make_request_in_queue(image=image_bytes, queue='echo')
        request_done = wait_for_request_done(request_id)
    except classes.AppServerTimeoutError:
        return error_response_service_unavailable(
            message='Request timeout. Please try again.')
    except Exception as e:
        print(e)
        return error_response_internal_server_error(
            message='Error during echo.')

    return request_done.results
예제 #2
0
def modifyuser(id):
    if "user_id" not in session:
        return redirect("/")
    if session["role"] != "admin":
        return render_template(
                "error.html",
                message="Sinulla ei ole oikeuksia tälle sivulle.")
    roles = users.get_roles()
    if request.method == "GET":
        user = users.get_user(id)
        return render_template(
                "modifyuser.html",
                user=user, 
                roles=roles)
    if request.method == "POST":
        if session["csrf_token"] != request.form["csrf_token"]:
            abort(403)
        if users.update_user(request.form):
            user = users.get_user(id)
            return render_template(
                    "modifyuser.html", 
                    user=user, 
                    roles=roles, 
                    message="Käyttäjätiedot päivitetty onnistuneesti!")
        else:
            return render_template(
                    "error.html", 
                    message="Käyttäjätietojen päivitys epäonnistui.")
예제 #3
0
	def GET(self):
		user = users.get_user()['username']
		access = users.get_user()['access']
		if access > 1:
			players = mongo.playerList(access)
			sizes = mongo.sectorSizes()
			hw = mongo.homeworldList()
			return render('dbstuff.html', players = players, sizes = sizes, hw = hw)
		else:
			return web.seeother('/')	
예제 #4
0
	def GET(self):
		user = users.get_user()['username']
		access = users.get_user()['access']
		if access >= 1:
			players = mongo.playerList(access)
			alliance = mongo.alliances(access)
			score_time = mongo.scoreTime()
			sector_time = mongo.sectorTime()
			return render('intelViewer.html', players = players, alliances = alliance, score_time = score_time, sector_time = sector_time, access = access)
		else:
			return web.seeother('/')
예제 #5
0
	def GET(self):
		st = time_stamp()
		user = users.get_user()['username']
		access = users.get_user()['access']
		if access >= 3:
			info = ""
			db.users.update({'username' : user},{"$push" :{'updates' : {'time' : st, 'action' : "View Users in Admin", 'info' : info}}})
			uws_users = mongo.userControl()
			return render('admin.html', access = uws_users)
		else:
			return web.seeother('/')
예제 #6
0
	def GET(self):
		user = users.get_user()['username']
		access = users.get_user()['access']
		if access > 2:
			map = db.map_time.find().sort('utime', -1).limit(1)
			for a in map:
				last_map = a['utime']
				
				print last_map
			return render('upload.html', last_map = last_map)
		else:
			return web.seeother('/')
예제 #7
0
	def POST(self):
		st = time_stamp()
		user = users.get_user()['username']
		access = users.get_user()['access']
		if access >= 3:
			uws_users = mongo.userControl()
			post = web.input(_method='POST')
			new_access_level = int(post['lvl'])
			update_user = post['user']
			user_updated = db.users.find_one({'_id' : ObjectId(post['user'])})['username']
			info = "%s updated to lvl %d" %(user_updated, new_access_level)
			db.users.update({'username' : user},{"$push" :{'updates' : {'time' : st, 'action' : "Update Users in Admin", 'info' : info}}})
			new_access = mongo.updateAccess(update_user, new_access_level)
			return render('admin.html', access = uws_users)
예제 #8
0
def add_server():

    user, err = users.get_user()
    if not user.exists:
        print('User [{}] does not exist'.format(user.username))
        input()
        return

    server = get_server()
    get_groups(server)

    ret, err = user.add_server(server)
    if not ret:
        print(err)
        input()
        return

    ret, err = user.write_to_db()
    if err:
        print('Error adding server: {}'.format(err))
    else:
        print('Server '+\
            '[{}] was successfully added!'.format(server["servername"]))

    input()
예제 #9
0
def owned_course(request):
    new_url=connections()
    url = "http://%s/course/list" % (new_url)
    email=request.session['email']
    general_list=get_user(request, email)
    print general_list
    owned_list=general_list.get('own')
    print owned_list
    if owned_list is None:
        return render_to_response('home.html',{'error':"sorry you had not uploaded any course yet"})
    data={}
    combined_data={}
    lists=[]
    for list in owned_list:
        print "this is list %s"%list
        data=get_course(request, list)
        print data
        old_data={"courseID":list}
        # appending courseId
        new_data = dict(data.items() + old_data.items())
        print "newly listed and updated data %s"%new_data
        lists.append(new_data)

        #combined_data.update(data)
    #print data
    print "New data %s"%lists
    return render_to_response('course_edit.html',{'data':lists})
예제 #10
0
    def POST(self, username):
        post = web.input(_method='POST')
        errors = {}
        user = users.get_user()

        contact = db.users.find_one({'username':username})

        forms.validate(errors, 'username', lang.NO_CONTACT_FOUND, lambda c: bool(c), (contact,))
        if contact:
            forms.validate(errors, 'username', lang.ALREADY_CONNECTED(contact['username']), lambda u, c: ('contacts' not in u) or (c not in u['contacts']), (user, contact))
            forms.validate(errors, 'username', lang.CANT_CONNECT_TO_SELF, lambda u, c: c!=u, (user, contact))

        if contact and not errors:
            #Add to the user's contacts
            if 'contacts' not in user or not user['contacts']:
                user['contacts'] = []
            user['contacts'].append(DBRef('users',contact['_id']))
            
            #Add user to the other persons contacts
            if 'contacts' not in contact or not contact['contacts']:
                contact['contacts'] = []
            contact['contacts'].append(DBRef('users',user['_id']))
            
            #Save them both
            db.users.save(user)
            db.users.save(contact)                                       

        return render('/users/profile.html', profile=contact, errors=errors, connected=self.connected(contact))    
예제 #11
0
파일: app.py 프로젝트: Xariec/web_game
 def GET(self):
     u_id = users.get_user()['_id']
     print u_id
     fleet = db.player_items.find({'u_id': u_id, 'item': "Ship"})
     ship_id = []
     name = []
     health = []
     type = []
     ship_fleet = []
     list_fleet = []
     count = 0
     list = 0
     for x in fleet:
         ship_id.append(x['_id'])
         name.append(x['name'])
         type.append(x['type'])
         health.append(x['health'])
         ship_fleet.append(x['fleet'])
         if (x['fleet'] in list_fleet) == False:
             list_fleet.append(x['fleet'])
             list += 1
         count += 1
     return render('fleet.html',
                   name=name,
                   type=type,
                   health=health,
                   count=count,
                   list=list,
                   list_fleet=list_fleet,
                   ship_fleet=ship_fleet,
                   ship_id=ship_id)
 def test_get_one_user(self, mock_get_users):
     """
     Test for getting one user using their userID
     Demonstrates mocking third party functions
     """
     users = [{
         'phone': '514-794-6957',
         'first_name': 'Brant',
         'last_name': 'Mekhi',
         'id': 0
     }, {
         'phone': '772-370-0117',
         'first_name': 'Thalia',
         'last_name': 'Kenyatta',
         'id': 1
     }, {
         'phone': '176-290-7637',
         'first_name': 'Destin',
         'last_name': 'Soledad',
         'id': 2
     }]
     mock_get_users.return_value = Mock()
     mock_get_users.return_value.json.return_value = users
     user = get_user(2)
     self.assertEqual(user, users[2])
예제 #13
0
def assert_broker():
    identity = get_jwt_identity()
    current_user = get_user(identity, brokers)
    if not current_user:
        raise Unauthorized(
            "Access denied, you have to be a broker to read this")
    return current_user
예제 #14
0
파일: server.py 프로젝트: jan25/tools
def update_user(user_id):
    if not request.is_json():
        return 'Request type is not json'
    json_data = request.get_json()
    if users.update_user(user_id, json_data):
        return 'User not updated'
    return users.get_user(user_id)
예제 #15
0
def single_user_endpoint(name):
    try:
        user = users.get_user(name=name)
    except classes.UserNotFoundError as e:
        return error_response_not_found(message=str(e))

    return success_response_with_json(user=user)
예제 #16
0
def add_recipe(name, ingredients, quantities, steps, image):
    username = users.get_user()
    if username is None:
        return False
    sql = "INSERT INTO Recipes (name) VALUES (:name) RETURNING id"
    result = db.session.execute(sql, {"name":name})
    recipe_id = result.fetchone()[0]
    for index, ingredient in enumerate(ingredients):
        sql = "SELECT id FROM Ingredients WHERE name=:name"
        result = db.session.execute(sql, {"name":ingredient})
        if result.rowcount == 0:
            sql = "INSERT INTO Ingredients (name) VALUES (:name) RETURNING id"
            result = db.session.execute(sql, {"name":ingredient})
        ingredient_id = result.fetchone()[0]
        sql = "INSERT INTO RecipeIngredients (recipe_id, ingredient_id, quantity) VALUES (:recipe_id, :ingredient_id, :quantity)"
        db.session.execute(sql, {"recipe_id":recipe_id, "ingredient_id":ingredient_id, "quantity":quantities[index]})
    for index, step in enumerate(steps):
        sql = "INSERT INTO Steps (recipe_id, step, instructions) VALUES (:recipe_id, :step, :instruction)"
        order_number = index + 1
        db.session.execute(sql, {"recipe_id":recipe_id, "step":order_number, "instruction":step})
    if image is not None:
        image_data = image.read()
        sql = "INSERT INTO Images (recipe_id, image) VALUES (:recipe_id, :image)"
        db.session.execute(sql, {"recipe_id":recipe_id, "image":image_data})
    db.session.commit()
    return True
예제 #17
0
    def on_post(self, req, resp):
        doc = req.context['doc']
        lat = doc['lat']
        lon = doc['lon']
        date_in = datetime.datetime.utcnow()
        if lat and lon:
            user = get_user(req, resp)

        if lon >= -79.8921061:
            if lon <= -79.8833942:
                if lat <= 36.0984408:
                    if lat >= 36.0903956:
                        signin = Signin(date_in=date_in, user=user)
                        user.signedin = True
                        Session.add(signin)
                        Session.commit()

                        resp.status = falcon.HTTP_201
                        resp.location = '/signins/%s' % (signin.id)
                        req.context['result'] = {"action": "sign in", "result": "success"}
            else:
                resp.status = falcon.HTTP_409
                req.context['result'] = {"action": "sign in", "result": "failure"}

        else:
            resp.status = falcon.HTTP_409
            req.context['result'] = {"action": "sign in", "result": "failure"}
예제 #18
0
    def on_post(self, req, resp):
        doc = req.context['doc']

        title = doc['title']
        description = doc['description']
        from_date = doc['from_date']
        to_date = doc['to_date']

        from_date_datetime = datetime.datetime.strptime(from_date, "%Y-%m-%d")
        to_date_datetime = datetime.datetime.strptime(to_date, "%Y-%m-%d")

        user = get_user(req, resp)

        event = Event(from_date=from_date_datetime, to_date=to_date_datetime, title=title,
                description=description, user=user)
        Session.add(event)
        Session.commit()

        resp.status = falcon.HTTP_201
        req.context['result'] = {"action": "add event", "result": "success",
                "event": {
                    'id': event.id,
                    'from_date': from_date,
                    'to_date': to_date,
                    'title': event.title,
                    'description': event.description
                }
            }
예제 #19
0
    def test_request_response_with_decorator(self, mock_get):

        mockuser = [{
            'phone': '514-794-6957',
            'first_name': 'Brant',
            'last_name': 'Mekhi',
            'id': 0
        }, {
            'phone': '772-370-0117',
            'first_name': 'Thalia',
            'last_name': 'Kenyatta',
            'id': 1
        }, {
            'phone': '176-290-7637',
            'first_name': 'Destin',
            'last_name': 'Soledad',
            'id': 2
        }]

        # Mock status code of response.
        mock_get.return_value.status_code = 200
        mock_get.return_value.json.return_value = mockuser
        response = get_users()

        # filter to find user 2
        user = get_user(2)

        # Assert that the request-response cycle completed successfully.
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), mockuser)
        self.assertEqual(user, mockuser[2])
예제 #20
0
파일: server.py 프로젝트: jan25/tools
def create_user():
    if request.is_json():
        return 'Request type is not json'
    json_data = request.get_json()
    user_id = users.create_user(json_data)
    if user_id is None:
        return 'User not updated'
    return users.get_user(user_id)
예제 #21
0
def get_user_and_account():
    user = None
    account = None
    if g.user_id:
        user = get_user(g.db, g.user_id)
    if user:
        account = get_account(g.db, user['account_id'])
    return user, account
예제 #22
0
파일: player.py 프로젝트: luispedro/hearts
 def hello(self,args):
     self.name=args.strip()
     self.user=get_user(self.name)
     if not self.user:
         self.error('unknownUser','Did you register at http://hearts.luispedro.org/?')
     else:
         self.cookie='chocolate_chip'
         self.output('authQ %s %s' % (_Authentication_Method,self.cookie))
예제 #23
0
def add_members(obj, srcId, dstId):
	# delete all the existing members first (objects' creator should be here)
	for mbr in map(lambda m: m['id'], obj.get_members(dstSys, dstId)):
		obj.del_member(dstSys, dstId, mbr)
	# return an user_id in the destination system according to a given member dict from the source system
	usr = Users()
	uidByMember = lambda mbr: get_user(dstSys, usr.by_id(srcSys, mbr['id']))
	for mbr in obj.get_members(srcSys, srcId):
		obj.add_member(dstSys, dstId, uidByMember(mbr), mbr['access_level'])
예제 #24
0
def get_user(userId):
    if userId is None:
        return False, None
    else:
        oneUser = users.get_user(userId)
        if oneUser is None:
            return False, None
        else:
            return True, oneUser
예제 #25
0
    def _deref_contacts(self):
        user = users.get_user()

        try:
            user.update({'contacts': mongo_utils.deref_list(db, user['contacts'])})
        except KeyError:
            user['contacts'] = []
            
        return user
예제 #26
0
def welcome(request):
    cookie = request.COOKIES['name']
    if cookie:
        user_id, cookie_hash = cookie.split('|')
        user = get_user(userid=user_id)
        if user and user.hashed_pw == cookie_hash:
            c = {'usr': user.username}
            return render_template(request, 'welcome.html', context=c)
    return redirect('/signup')
예제 #27
0
파일: 知乎.py 프로젝트: cone387/ZhiHu
 def run(self):
     start_time = time.time()
     pwd = get_user("zh")
     self.login("18895379450", pwd)
     # 从我的主页开始爬取
     self.user_links.append("/people/bi-zhong-liang-33")
     self.get_followings()
     time_used = time.time() - start_time
     print u"一共用时%s秒" % time_used
예제 #28
0
    def POST(self):
        post = web.input(_method='POST')
        errors = {}
        user = users.get_user()
        mode = ''

        #Get all the stuff we want from POST
        if 'from_username' in post:
            mode = 'from'
            other_username = forms.get_or_add_error(post, '%s_username' % mode, errors, lang.NO_FIELD_SUPPLIED('username'))
        else:
            mode = 'to'
            other_username = forms.get_or_add_error(post, '%s_username' % mode, errors, lang.NO_FIELD_SUPPLIED('username'))

        value_pounds = forms.get_or_add_error(post, '%s_value_pounds' % mode, errors, lang.NO_FIELD_SUPPLIED('pounds value'))
        value_pence  = forms.get_or_add_error(post, '%s_value_pence' % mode, errors, lang.NO_FIELD_SUPPLIED('pence value'))
        reason  = forms.get_or_add_error(post, '%s_reason' % mode, errors, lang.NO_FIELD_SUPPLIED('reason'))

        #Process and validate the amount
        try:
            if value_pounds.strip() == '':
                value_pounds = 0
            if value_pence.strip() == '':
                value_pence = 0

            value_pounds = int(value_pounds)
            value_pence = int(value_pence)
            if value_pounds < 0 or value_pence < 0:
                raise Exception

            if value_pounds != None and value_pence != None:
                forms.validate(errors, '%s_value' % mode, lang.MUST_BE_GREATER_THAN_ZERO('Value'), lambda po,pe: (po+pe*100)>0, (value_pounds,value_pence))
        except:
            errors['%s_value' % mode] = lang.MUST_BE_POS_INTEGER('Pounds and pence')
            
        #Validate the reason
        forms.validate(errors, '%s_reason' % mode, lang.NO_FIELD_SUPPLIED('reason'), lambda r: bool(r), (reason,))

        #Validate and get the other user
        if other_username:
            other_user = db.users.find_one({'username':other_username})
            forms.validate(errors, '%s_username' % mode, lang.NO_CONTACT_FOUND, lambda u: bool(u), (other_user,))

        #Now do the rendering
        if not errors:
            value = round((float(value_pounds)*100 + float(value_pence)) / 100.0, 2)
            
            if mode == 'to':
                from_user, to_user = user, other_user
            else:
                from_user, to_user = other_user, user

            trans = db.transactions.save({'from_user': from_user['_id'], 'to_user': to_user['_id'], 'value':value, 'timestamp':time.time(), 'reason':reason})

            return render('transfer.html', success=True, user=self._deref_contacts(), from_user=from_user, to_user=to_user, value="%.2f" % value, mode=mode)
        else:
            return render('transfer.html', errors=errors, user=self._deref_contacts())
예제 #29
0
	def GET(self):
		user = users.get_user()['username']
		if user == "Xariec":
			site_users = []
			query = db.users.find()
			for a in query:
				site_users.append((a))
				
			return render('xariec.html', site_users = site_users)
예제 #30
0
def create_timeline(user_id, name, description):
    luser = users.get_user(user_id)
    if luser is None:
        # TODO(dasarathi): create error handling, throw exceptions?
        return
    timeline = Timeline(name=name, description=description, user_id=user_id)
    timeline_key = timeline.put()
    luser.timeline_ids.append(timeline_key.id())
    return timeline_key.id()
예제 #31
0
def create_timeline(user_id, name, description):
  luser = users.get_user(user_id)
  if luser is None:
    # TODO(dasarathi): create error handling, throw exceptions?
    return
  timeline = Timeline(name=name, description=description, user_id=user_id)
  timeline_key = timeline.put()
  luser.timeline_ids.append(timeline_key.id())
  return timeline_key.id()
예제 #32
0
def get_user(userId):
    if userId is None:
        return False,None
    else:
        oneUser = users.get_user(userId)
        if oneUser is None:
            return False, None
        else:
            return True, oneUser
예제 #33
0
def format_transaction(db, t):
    u = users.get_user()

    to_user = None if u['_id'] == t['to_user'] else db.users.find_one(t['to_user'])
    from_user = None if u['_id'] == t['from_user'] else db.users.find_one(t['from_user'])

        
    t.update({'from_user':from_user, 'to_user':to_user, 'value':u'£%.2f' % t['value'], 'timestamp': time.strftime('%d %b %Y',time.localtime(t['timestamp']))})
    return t
예제 #34
0
def render(uri, **kwargs):
    if 'user' not in kwargs:
        kwargs['user'] = users.get_user()

    try:
        template = lookup.get_template(uri)
        output = template.render_unicode(**kwargs)
        return output
    except:
        return mako.exceptions.html_error_template().render()
예제 #35
0
파일: web.py 프로젝트: dmc2015/mpt
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        user = users.get_user(username, password)
        if user and user.is_authenticated():
            login_user(user, remember=True)
            return redirect(request.args.get("next") or '/')
        return redirect('/login')
    return render_template("login.html")
예제 #36
0
def render(uri, **kwargs):
    if 'user' not in kwargs:
        kwargs['user'] = users.get_user()

    try:
        template = lookup.get_template(uri)
        output = template.render_unicode(**kwargs)
        return output
    except:
        return mako.exceptions.html_error_template().render()
예제 #37
0
def user_quota_endpoint():
    try:
        token = get_token(request)
        user = users.get_user(token=token)
    except classes.UserAuthenticationError as bad_token_error:
        return error_response_unauthorized(message=str(bad_token_error))
    except classes.UserNotFoundError:
        return error_response_unauthorized(
            message='No user associated with the token <{}>.'.format(token))

    return success_response_with_json(quota=user['quota'], tier=user['tier'])
예제 #38
0
파일: websrv.py 프로젝트: Leo-C/webshscr
def get_users(is_admin):
    if is_admin:
        names = get_user_names()
    else:
        names = []
        names.append(current_user.name)
    users = []
    for name in names:
        users.append((name, ",".join(get_user(name).groups)))
    
    return users
예제 #39
0
def on_query_connections(data):
    result = []
    response = []
    try:
        result = (db.session.query(tables.Connections).filter(
            (tables.Connections.user1_email == data["user_email"])
            | (tables.Connections.user2_email == data["user_email"])).all())
        db.session.close()
        for connection in result:
            if connection.user1_email == data["user_email"]:
                connected_user = users.get_user(connection.user2_email)
                if connected_user != None:
                    response.append(connected_user)
            elif connection.user2_email == data["user_email"]:
                connected_user = users.get_user(connection.user1_email)
                if connected_user != None:
                    response.append(connected_user)
        return response
    except Exception as err:
        print(err)
예제 #40
0
def on_new_connection(data):
    try:
        for connection in (db.session.query(tables.Connections).filter(
            (tables.Connections.user1_email == data["user1_email"])
                &
            (tables.Connections.user2_email == data["user2_email"])).all()):
            return users.get_user(data["user2_email"])
        for connection in (db.session.query(tables.Connections).filter(
            (tables.Connections.user1_email == data["user2_email"])
                &
            (tables.Connections.user2_email == data["user1_email"])).all()):
            return users.get_user(data["user2_email"])

        db.session.add(
            tables.Connections(data["user1_email"], data["user2_email"]))
        db.session.commit()
        db.session.close()
        return users.get_user(data["user2_email"])
    except:
        return {"success": False}
예제 #41
0
def main():
    # get new message from queue
    events = queue.get_queue('IngressQueue')
    for event in events:
        d = event.get_body()
        d = json.loads(d)
        uid = d['from']
        message = d['message']

        # lookup user

        try:
            curr_user = users.get_user(uid)
        except ItemNotFound:
            curr_user = users.EndUser(uid)
            curr_user.write()

        print curr_user
        print curr_user.last_question
        # process question
        if curr_user.last_question is None:
            send_first_question(uid, event, curr_user)
            break
        else:
            question = questions.get_question(curr_user.last_question)

        for q, v in question.answers.iteritems():

            v_json = json.loads(v)

            print v[1].lower()
            if message.lower() == v_json.values()[0].lower():
                print "response match found"
                next_question_id = json.loads(question.child_questions[q])
                print next_question_id.values()[0]
                # create response message & publish to queue
                next_question = questions.get_question(
                    next_question_id.values()[0])
                queue.put_queue(
                    json.dumps({
                        'to': uid,
                        'message': next_question.qstring
                    }), 'EgressQueue')
                queue.delete_from_queue(event, 'IngressQueue')
            else:
                print "unable to find a response match"
                # invalid response
                queue.put_queue(
                    json.dumps({
                        'to': uid,
                        'message': "Sorry, that wasn't a valid response"
                    }), 'EgressQueue')
                queue.delete_from_queue(event, 'IngressQueue')
                break
예제 #42
0
파일: routes.py 프로젝트: acidmole/teammate
def edit_user(id):
	if users.is_admin() or users.user_id() == id:
		form = EditInfoForm(request.form)
		user = users.get_user(id)
		if players.is_player(id):
			player_id = players.get_player_id(id)
			player = players.get_player(player_id[0])
			return render_template("edit_user.html", user=user, player=player, form=form)
		else:
			return render_template("edit_user.html", user=user, form=form)
	else:
		return render_template("error.html", message="Ei oikeutta")
예제 #43
0
    def handle_loc(message):
        check_user(message)
        cid = message.chat.id
        uid = message.from_user.id
        user = users.get_user(uid)

        bot.send_message(cid,
                         'Мы получили геолокацию',
                         reply_markup=global_markup)
        user.location = message.location
        user.is_have_location = True
        users.save_users()
예제 #44
0
파일: app.py 프로젝트: Xariec/web_game
 def POST(self):
     u_id = users.get_user()['_id']
     post = web.input(_method='POST')
     try:
         button = post['button']
     except:
         print post
     if button:
         people = web_actions.Population()
         single = people.getOnePersonnel(button, u_id)
         button = people.getAllPersonnel(u_id)[1]
         print single
         return render('personnel.html', button=button, single=single)
예제 #45
0
def rate(recipe_id, rating):
    username = users.get_user()
    if username is None:
        return False
    user_id = users.get_id()
    sql = "INSERT INTO Ratings(recipe_id, rating, user_id) VALUES (:recipe_id, :rating, :user_id)"
    db.session.execute(sql, {
        "recipe_id": recipe_id,
        "rating": rating,
        "user_id": user_id
    })
    db.session.commit()
    return True
예제 #46
0
    def post(self):
        """
        Refresh access token

        :raises Unauthorized: When JWT identity is invalid
        """
        current_user = get_user(get_jwt_identity(), everyone)
        if not current_user:
            raise Unauthorized("Invalid user")
        ret = {
            'access_token': create_access_token(identity=current_user),
        }
        return ret
예제 #47
0
def get_rating_status(recipe_id):
    username = users.get_user()
    if username is None:
        return True
    user_id = users.get_id()
    sql = "SELECT COUNT(*) FROM Ratings WHERE recipe_id=:recipe_id AND user_id=:user_id"
    result = db.session.execute(sql, {
        "recipe_id": recipe_id,
        "user_id": user_id
    })
    count = result.fetchone()[0]
    if count:
        return True
    return False
예제 #48
0
def login(request):
    if request.method == 'GET':
        return render_template(request, 'login.html')
    elif request.method == 'POST':
        usr = request.POST['username']
        pw = request.POST['password']
        user = get_user(username=usr)
        if user:
            hashed = hash_password(pw, salt=user.salt)[0]
            if hashed == user.hashed_pw:
                return successful_login(request, user)
        else:
            c = {'error': 'invalid login'}
            return render_template(request, 'login.html', context=c)
예제 #49
0
def users_route(user_id=None):
    if request.method == 'POST':
        first_name = utils.get_field(request, 'first_name', required=True)
        last_name = utils.get_field(request, 'last_name', required=True)
        email = utils.get_field(request, 'email', required=True)
        password = utils.get_field(request, 'password')
        fb_id = utils.get_field(request, 'fb_id')

        return users.new_user(first_name, last_name, email, password, fb_id)

    if user_id is None:
        return users.get_all_users()

    return users.get_user(user_id)
예제 #50
0
    def post(self):
        """
        Perform a login to access restricted API endpoints.

        :raises BadCredentials: In case of invalid credentials.
        """

        email = api.payload["email"]
        password = api.payload["password"]

        if not check_user(email, password):
            raise BadCredentials()

        user = get_user(email, everyone)
        return generate_login_response(user)
예제 #51
0
def main():
    # get new message from queue
    events = queue.get_queue('IngressQueue')
    for event in events:
        d = event.get_body()
        d = json.loads(d)
        uid = d['from']
        message = d['message']

        # lookup user

        try:
            curr_user = users.get_user(uid)
        except ItemNotFound:
            curr_user = users.EndUser(uid)
            curr_user.write()

        print curr_user
        print curr_user.last_question
        # process question
        if curr_user.last_question is None:
            send_first_question(uid, event, curr_user)
            break
        else:
            question = questions.get_question(curr_user.last_question)

        for q, v in question.answers.iteritems():

            v_json = json.loads(v)

            print v[1].lower()
            if message.lower() == v_json.values()[0].lower():
                print "response match found"
                next_question_id = json.loads(question.child_questions[q])
                print next_question_id.values()[0]
                # create response message & publish to queue
                next_question = questions.get_question(next_question_id.values()[0])
                queue.put_queue(json.dumps({'to': uid,
                                            'message': next_question.qstring}), 'EgressQueue')
                queue.delete_from_queue(event, 'IngressQueue')
            else:
                print "unable to find a response match"
                # invalid response
                queue.put_queue(json.dumps({'to': uid,
                 'message': "Sorry, that wasn't a valid response"}), 'EgressQueue')
                queue.delete_from_queue(event, 'IngressQueue')
                break
예제 #52
0
def login():
    """Logs the user in."""
    if g.user:
        return redirect(url_for('hardware.control'))
    error = None
    if request.method == 'POST':
        user = get_user('username', request.form['username'])
        if user is None:
            error = 'Invalid username'
        elif not check_password_hash(user['password_hash'],
                                     request.form['password']):
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
            session['user_id'] = user['user_id']
            return redirect(url_for('hardware.control'))
    return render_template('login.j2', error=error)
예제 #53
0
    def on_get(self, req, resp):
        user = get_user(req, resp)

        if user.is_admin():
            signins = Session.query(Signin).all()
        else:
            signins = Session.query(Signin).filter_by(user=user).all()

        signins_json = []
        for signin in signins:
            date = signin.date_in.strftime("%Y-%m-%d")
            signins_json.append({'id': signin.id, 'date': date})

        req.context['result'] = {
                'action': 'get signins',
                'result': 'success',
                'signins': signins_json
        }

        resp.status = falcon.HTTP_200
예제 #54
0
def add_points():
    while True:
        try:
            r = urllib.request.urlopen("http://tmi.twitch.tv/group/user/"+cfg.CHANNEL_NAME+"/chatters")
        except urllib.error.HTTPError as e:
            print(e.code, e.reason)
            continue
        chattersJson = json.loads(r.read().decode("utf-8"))
        for key in chattersJson['chatters']:
            for name in chattersJson['chatters'][key]:
                user = users.get_user(name)
                user['points']+=cfg.PPM
                if name.lower() == cfg.CHANNEL_NAME.lower():
                    user['status'] = 2
                elif key!='viewers':
                    user['status'] = 1
                else:
                    user['status'] = 0
                users.update_user(user)
        sleep(60)
예제 #55
0
def register():
    """Registers the user."""
    # if g.user:
        # return redirect(url_for('timeline'))
    error = None
    if request.method == 'POST':
        if not request.form['username']:
            error = 'You have to enter a username'
        elif not request.form['email'] or \
                '@' not in request.form['email']:
            error = 'You have to enter a valid email address'
        elif not request.form['password']:
            error = 'You have to enter a password'
        elif request.form['password'] != request.form['password2']:
            error = 'The two passwords do not match'
        elif get_user('username', request.form['username']) is not None:
            error = 'The username is already taken'
        else:
            add_user(request.form['username'], request.form[
                     'password'], request.form['email'])
            flash(
                'You were successfully registered and can login now', 'success')
            return redirect(url_for('login'))
    return render_template('register.j2', error=error)
예제 #56
0
    def on_get(self, req, resp):
        user = get_user(req, resp)

        events = Session.query(Event).all()

        events_json = []
        for event in events:
            from_date = event.from_date.strftime("%Y-%m-%d")
            to_date = event.to_date.strftime("%Y-%m-%d")
            events_json.append({
                'id': event.id,
                'from_date': from_date,
                'to_date': to_date,
                'title': event.title,
                'description': event.description
            })

        req.context['result'] = {
                'action': 'get events',
                'result': 'success',
                'events': events_json
        }

        resp.status = falcon.HTTP_200
예제 #57
0
 def enter_password(self, user):
     self.driver.find_element(*LoginPageLocatars.PASSWORD).send_keys(users.get_user(user)["password"])
예제 #58
0
 def enter_email(self, user):
     self.driver.find_element(*LoginPageLocatars.EMAIL).send_keys(users.get_user(user)["email"])
예제 #59
0
def before_request():
    g.user = None
    if 'user_id' in session:
        g.user = get_user('user_id', session['user_id'])