Ejemplo n.º 1
0
def sign_in_user(organization, username):
    username = request.authorization["username"]
    password = request.authorization["password"]
    user = User(db, organization, username)
    try:
        if user.verify_password(password):
            rtn = user.get
            rtn.append(organization)
            rtn.append(
                create_access_token(
                    identity=({
                        "username": user.username,
                        "fullname": "%s %s" % (user.name, user.surname),
                        "role": user.role_name,
                        "time": str(datetime.datetime.today()),
                        "organization": user.organization,
                        "id": user.user_id
                    })))
            log_activity(request.remote_addr, username, request.endpoint)
            return jsonify(rtn)
        else:
            return jsonify("Wrong Password")
    except IndexError:
        return jsonify("Wrong Username")
    except:
        return jsonify("An error occurred")
Ejemplo n.º 2
0
def menu_command(message):
    lang = get_lang(message.chat.id)

    if User.User(message.chat.id).type_u == 'unlogined':
        botHelper.send_mes(msgs[lang]['common']['new_user'], message.chat.id)
    else:
        if User.User(message.chat.id).type_u == 'student':
            markup = mkp.create(lang, [
                cbt.course_list_of('all', lang),
                cbt.course_list_of('my', lang)
            ],
                                include_back=False)

            botHelper.send_mes(msgs[get_lang(
                message.chat.id)]['common']['menu'],
                               message.chat.id,
                               markup=markup)
        else:
            markup = mkp.create(lang, [
                cbt.course_list_of('all', lang),
                cbt.course_list_of('my', lang)
            ], [tbt.manage_list(lang)], [tbt.new_course(lang)],
                                include_back=False)

            botHelper.send_mes(msgs[get_lang(
                message.chat.id)]['common']['menu'],
                               message.chat.id,
                               markup=markup)
Ejemplo n.º 3
0
def course_list(call, lang):
    if call.data['type'] == 'all':  # TODO не добавлять закрытые курсы
        courses = [i for i in Course.fetch_all_courses()]
        text = msgs[lang]['common']['all']
    elif call.data['type'] == 'my':
        courses = [i for i in User.User(call.message.chat.id).participation]
        text = msgs[lang]['common']['my']
    elif call.data['type'] == 'teach':
        courses = [i for i in User.User(call.message.chat.id).possessions]
        text = msgs[lang]['common']['teach']
    else:
        botHelper.error(call=call)
        return
    page = call.data['page']

    p = UI.Paging(courses, sort_key='name')
    text += p.msg(call.data['page'], lang)
    if call.data['type'] == 'teach':
        markup = mkp.create_listed(lang, tbt.courses(p.list(page)),
                                   tbt.manage_list, lang, page)
    else:
        markup = mkp.create_listed(lang, cbt.courses(p.list(page)),
                                   cbt.course_list_of, call.data['type'], lang,
                                   page)
    botHelper.edit_mes(text, call, markup=markup)
Ejemplo n.º 4
0
def test_load_user():
    #setup
    copy('test-db.json', 'db.json')

    #load user clay from db
    assert User.User(
        "111878986403861738670", "Clay James",
        "*****@*****.**") == app.loadUser("111878986403861738670")

    #load user joshua from db
    assert User.User(
        "112242778374526994969", "Joshua Dotson",
        "*****@*****.**") == app.loadUser("112242778374526994969")

    #load user roger from db
    assert User.User(
        "107379256252231037647", "Roger Cooper",
        "*****@*****.**") == app.loadUser("107379256252231037647")

    #load user justin from db
    assert User.User(
        "116982725875632556390", "justin mckenna",
        "*****@*****.**") == app.loadUser("116982725875632556390")

    #cleanup
    os.remove('db.json')
Ejemplo n.º 5
0
    def post(self):
        json_data = request.get_json(force=True)

        if not json_data:
            return {'message': 'No input data provider'}, 400

        user = User.query.filter_by(username=json_data['username']).first()
        if user:
            return {'message': 'User already exists'}, 400

        user = User.query.filter_by(email=json_data['email']).first()
        if user:
            return {'message': 'email already exists'}, 400

        api_key = self.generate_key()

        user = User.query.filter_by(api_key=api_key).first()
        if user:
            return {'message': 'API key already exists'}, 400

        user = User(api_key=api_key,
                    username=json_data['username'],
                    firstname=json_data['firstname'],
                    lastname=json_data['lastname'],
                    password=json_data['password'],
                    email=json_data['email'])

        db.session.add(user)
        db.session.commit()

        result = User.serialize(user)

        return {"data": result, "status": "success"}, 201
Ejemplo n.º 6
0
def api_register_user(*, email, name, passwd):
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')
    users = yield from User.findAll('`email`=?', email)
    if len(users) > 0:
        raise APIError('register:failed', 'email', 'Email is already in use')
    uid = next_id()
    sha1_passwd = '%s:%s' % (uid, passwd)
    user = User(id=uid,
                name=name.strip(),
                email=email,
                passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(),
                image='http://www.gravatar.com/avatar/%s?d=mm&s=120' %
                hashlib.md5(email.encode('utf-8')).hexdigest())
    yield from user.save()
    r = web.Response()
    r.set_cookie(COOKIE_NAME,
                 user2cookie(user, 86400),
                 max_age=86400,
                 httponly=True)
    user.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
Ejemplo n.º 7
0
async def api_register_user(*, email, name, passwd):
    # print('type of request= ------------',type(request))
    # print(request)
    # print(request.items())
    # print(type(request['request']))
    # print(dir(request['request']))
    # print(request['request'].json)
    print(email, name, passwd)

    # 判断name是否存在,且是否只是'\n', '\r',  '\t',  ' ',这种特殊字符
    if not name or not name.strip():
        raise APIValueError('name')
    # 判断email是否存在,且是否符合规定的正则表达式
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    # 判断passwd是否存在,且是否符合规定的正则表达式
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')

    #检测数据库中是否有相同的email地址,如果有,提示用户email已被注册
    users = await User.findAll('email=?', [email])
    if len(users) > 0:
        raise APIValueError('register:failed', 'email', 'Email is already in use.')

    #生产注册用户唯一uid
    uid = next_id()
    #构建sha1_passwd
    sha1_passwd = '%s:%s' % (uid,passwd)

    admin = False
    if email == '*****@*****.**':
        admin = True

    #创建用户
    user = User(
        id=uid,
        name=name.strip(),
        email=email,
        #密码存储用sha1算法转化
        passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), 
        #存储头像图床地址
        image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest(), 
        admin=admin
        )
    await user.save()
    logging.info('save user ok')

    r = web.Response()
    #添加cookie
    r.set_cookie(COOKIE_NAME,user2cookie(user,86400),max_age=86400,httponly=True)
    #把返回的实例的密码改成‘**************’,防止密码泄露
    user.passwd = '*******'
    #返回的shijson,所及设置content-type为json
    r.content_type = 'application/json'
    #把对象转换成json格式
    r.body = json.dumps(user,ensure_ascii=False).encode('utf-8')
    return r
Ejemplo n.º 8
0
def getUserEntity(user):

	entity = User.all().filter('user =',user).get()

	if not entity:
		entity = User(user=user)
		entity.put()

	return entity
Ejemplo n.º 9
0
 def post(self):
     game = GameFromRequest(self.request).get_game()
     ai = User.get_by_id(AI_ID)
     if not ai:
         logging.info('Failed to retrieve AI user')
     if not game.userO:
         game.userO = User.get_by_id(AI_ID)
         game.put()
         GameUpdater(game).send_update()
Ejemplo n.º 10
0
def test_add_data(connect):
    u1 = User(name='Light', age=23)
    u2 = User(name='Ash', age=20)
    r = Role(name='user')
    connect.add(u1)
    connect.add(u2)
    connect.add(r)
    connect.commit()
    assert connect.query(User).all() != []
    assert connect.query(Role).all() != []
Ejemplo n.º 11
0
 def test_legal_moves(self):
     userX = User()
     userX.put()
     myGame = Game(userX,
                 moveX = True,
                 last_cell = 1,
                 all_mini_wins = [' ']*9,
                 metaboard = ['         ']*9)
     legal_moves = getLegalMoves(myGame)
     self.assert_(legal_moves == [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8)], msg=str(legal_moves))
Ejemplo n.º 12
0
def reset_password(organization, username):
    user = User(db, organization, username)
    if request.method == "GET":
        rtn = jsonify(user.reset_password())
    else:
        rtn = jsonify(
            user.check_and_change_password(
                request.authorization["username"],
                new_pass=request.authorization["password"]))
    log_activity(request.remote_addr, username, request.endpoint)
    return rtn
Ejemplo n.º 13
0
 def test_ai(self):
     userX = User()
     userX.put()
     foo = 6
     myGame = Game(userX,
                 moveX = True,
                 last_cell = 4,
                 all_mini_wins = [' ']*9,
                 metaboard = ['         ']*9)
     result = negamax(myGame, 7, float('-inf'), float('inf'))
     self.assertEqual(result, (0, (4, 0)))
Ejemplo n.º 14
0
    def done(self):
        # make sure the user doesn't already exist
        u = User.by_name(self.username)
        if u:
            msg = 'That user already exists.'
            self.render('signup-form.html',
                        error_username=msg,
                        username=self.username)
        else:
            u = User.register(self.username, self.password, self.email)
            u.put()

            self.login(u)
            self.redirect('/blog')
Ejemplo n.º 15
0
def change_password(organization, username):
    token = get_jwt_identity()
    user = User(db, token["organization"], token["username"])
    if username != user.username or user.organization != organization:
        return jsonify("Unauthorized access!")
    ismail = request.form["isMail"]
    if ismail == "True":
        ismail = True
    else:
        ismail = False
    rtn = jsonify(
        user.change_password_or_email(request.form["Password"],
                                      request.form["newPassword"], ismail))
    log_activity(request.remote_addr, token["username"], request.endpoint)
    return rtn
Ejemplo n.º 16
0
def command_start(m):
    cid = m.chat.id
    check = find_user_by_tg(m.chat.username.lower())
    if (check):
        if (check.chatid):
            bot.send_message(
                cid, "I already know you, no need for me to scan you again!")
        else:
            check.chatid = cid
            check.save()
            bot.send_message(cid, "Hello, stranger, let me scan you...")
            bot.send_message(cid, "Scanning complete, I know you now")
    else:
        check = User(tname=m.chat.username.lower(), chatid=cid)
        check.save()
Ejemplo n.º 17
0
def register():
    form = Registration()
    if form.validate_on_submit():
        print form.username.data
        #if username/email is already used
        if Acc.query.filter_by(username=form.username.data).first():
            flash('Username already exists. Try a different username.',
                  'danger')
            return redirect(url_for('register'))
        if Acc.query.filter_by(email=form.email.data).first():
            flash('Email already used. Use a different email address.',
                  'danger')
            return redirect(url_for('register'))
        #if user,email does not exist yet, and passwords match, register.
        newacc = Acc(username=form.username.data,
                     password=form.password.data,
                     email=form.email.data)
        db.session.add(newacc)
        db.session.commit()
        #user is an account. so create account first before assigning user.
        user = User(Acc.get_id(newacc), form.fname.data, form.lname.data, '')
        db.session.add(user)
        db.session.commit()
        flash('Account created for {name}!'.format(name=form.username.data),
              'success')
        return redirect(url_for('login'))
    return render_template('register.html', form=form)
Ejemplo n.º 18
0
def cookie2user(cookie_str):
    '''
    Parse cookie and load user if cookie is valid.
    '''
    if not cookie_str:
        return None
    try:
        L = cookie_str.split('-')
        if len(L) != 3:
            return None
        uid, expires, sha1 = L
        if int(expires) < time.time():
            return None
        user = yield from User.find(uid)
        if user is None:
            return None
        s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY)
        if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest():
            logging.info('invalid sha1')
            return None
        user.passwd = '******'
        return user
    except Exception as e:
        logging.exception(e)
        return None
Ejemplo n.º 19
0
def user_attendance(users, course_id, class_id):
    arr = []

    cw = Course.Classwork(course_id, class_id)

    for user in users:
        button = InlineKeyboardButton(User.User(user.id).name if cw.attendance(
            user.id).value else User.User(user.id).name + '*',
                                      callback_data=dumps(
                                          dict(type='sw_attend',
                                               id=course_id,
                                               id_u=user.id,
                                               id_cl=class_id)))
        arr.append(button)

    return arr
    def deRegisterUser(self, userName): #(long userID):    
        
        ''' To do:
                Remove the entries for the userID from the DB
                Remember to deregister from the jabber server as well apart from this. 
            '''
        try:
            u = User.get(User.username==userName)
            sensorObjects = SensorUserRel.select().where(SensorUserRel.user==u)
            for i in sensorObjects:
                i.delete_instance()
            queryObjects = Query.select().where(Query.username==u)
            for i in queryObjects:
                i.delete_instance()
            u.delete_instance()
        except User.DoesNotExist:
            print 'User ' + str(userName) + ' does not exist. Returning delete ACK anyway.'
        except:
            print 'Unknown error; returning!'
            return
        
        print str(userName) + " deleted successfully!"
        self.msgHandler.send_message(mto=str(self.rMessage['from']).split("/")[0], msubject="De-Registration Successful", mbody="Thank you!")

        return
Ejemplo n.º 21
0
def username_available(username, user, session):

    users = User.find_username(username)
    groups = Group.find_username(username)

    available = not users and not groups
    return response({'username': username, 'available': available})
Ejemplo n.º 22
0
def user_mark(id_u, id_c, id_t):
    task = Course.Task(id_c, id_t)

    arr = []
    for i in id_u:
        name = User.User(i).name if task.mark(
            i).value is not None else User.User(i).name + '*'
        button = InlineKeyboardButton(name,
                                      callback_data=dumps(
                                          dict(type='mark_u_o',
                                               id=id_c,
                                               id_u=i,
                                               id_t=id_t)))
        arr.append(button)

    return arr
    def queryPossible(self):
        '''Check from the database if we even have the requested number of devices to service the query.'''
        #if found return True
        #To Write a SELECT query when DB Schema finalized.
        #assuming no future queries for now
        #Untested code
        if self.queryDBObject.frequency==0:
            u=Sensor.select().where((str(self.queryObject['dataReqd'])== Sensor.SensorType)).distinct()
        else:
            u=Sensor.select().where((str(self.queryObject['dataReqd'])== Sensor.SensorType)&((Sensor.minDelay==0)|(eval(str(self.queryObject['frequency']))<1000000.0/Sensor.minDelay)) ).distinct()
        z = User.select().join(SensorUserRel).where(SensorUserRel.sensor << u).distinct()

        ''' Possible query to get all users of such sensors in u:
         z = User.select().join(SensorUserRel).where(SensorUserRel.sensor << u).distinct()
         '''
        lat1 = self.queryDBObject.Latitude
        lon1 = self.queryDBObject.Longitude
        if self.queryDBObject.Radius<0 or lat1<0 or lon1<0:
            ''' Radius to not be considered! '''
            for i in z:
                self.providerList += [i]
        else:
            R = self.queryDBObject.Radius
            for i in z:
                if self.getDistanceInKM(lon1, lat1, i.Longitude, i.Latitude) <= R:
                    self.providerList += [i]
            
        print 'Found count=' + str(len(self.providerList)) + ' for query Number: ' + self.queryNo
        
        if(len(self.providerList)>=eval(str(self.queryObject['countMin']))):
            #Query is possible; initiate messages to valid subscribers to respond with an acknowledgement.            
            return True
        else:
            return False
Ejemplo n.º 24
0
def authenticate(*, email, passwd):
    if not email:
        raise APIValueError('email', 'Invalid email.')
    if not passwd:
        raise APIValueError('passwd', 'Invalid passwd.')
    users = yield from User.findAll('`email`=?', email)
    if len(users) == 0:
        raise APIValueError('Email', 'Email not exist.')
    user = users[0]
    # check passwd
    sha1 = hashlib.sha1()
    sha1.update(user.id.encode('utf-8'))
    sha1.update(b':')
    sha1.update(passwd.encode('utf-8'))

    if user.passwd != sha1.hexdigest():
        logging.info('passwd:%s,sha1:%s' % (user.passwd, sha1.hexdigest()))
        raise APIValueError('passwd', 'password error.')
    r = web.Response()
    r.set_cookie(COOKIE_NAME,
                 user2cookie(user, 86400),
                 max_age=86400,
                 httponly=True)
    user.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
Ejemplo n.º 25
0
def migrate_to_db(data):

	userDBOPS = UserCRUD()
	attendanceDBOPS = AttendanceDetailCRUD()	
	
	for i in range(len(data)):
	    name = data.loc[i]['Name']
	    email = data.loc[i]['Email']    
	    join_time = data.loc[i]['Join Time']
	    leave_time = data.loc[i]['Leave Time']
	    duration = data.loc[i]['Duration(Minutes)']
	    alternative_score = data.loc[i]['Alternative Score']
	    course_id = data.loc[i]['CourseID']	    
	    
	    user = User(name, email)
	    
	    attendance_detail = AttendanceDetail(join_time,
	                                               leave_time,
	                                               duration, 
	                                               alternative_score,
	                                               email,
	                                               course_id                                                
	                                        )
	    

	    user_db = userDBOPS.record_exists(user)	    


	    if user_db == None:
	        userDBOPS.insert_record(user)	   

	    if attendanceDBOPS.record_exists(attendance_detail) == None:
	        attendanceDBOPS.insert_record(attendance_detail)
Ejemplo n.º 26
0
def customer_id_to_object(userid):
    conn = mysql.connect()
    cursor = conn.cursor()
    cursor.execute('select U.userid, U.registrationdate, U.username, U.password, U.firstname, U.lastname, u.address, u.city, u.state, u.zipcode, u.telephone, u.email, u.rating  from UserData U where U.userid=%s', (userid))
    d = cursor.fetchone()
    user = User(userid=d[0], registrationdate=d[1], username=d[2], password=d[3], firstname=d[4], lastname=d[5], address=d[6], city=d[7], state=d[8], zipcode=d[9], telephone=d[10], email=d[11], rating=d[12])
    return user
Ejemplo n.º 27
0
    def post(self, user_id):
        data = {}
        
        # the values in request.arguments are stored as single value lists
        # we need to extract their string values
        for arg in self.request.arguments():
            data[arg] = self.request.get(arg)

        # If there is no txn_id in the received arguments don't proceed
        if data['txn_type'] == 'subscr_payment' and not 'txn_id' in data:
            logging.info('IPN: No Parameters')
            return

        User.buyFor(user_id)
        # Verify the data received with Paypal
        if not self.request.host.split(':')[0] == 'localhost' and not self.verify_ipn(data):
            logging.info('IPN: Unable to verify')
            return

        logging.info('IPN: Verified!')
        logging.info(data)


        # Now do something with the IPN data
        # if data['txn_type'] == 'express_checkout' or data['txn_type'] == 'web_accept':
        #     #======== BUY  ===== !!!!

        if data['txn_type'] == 'subscr_signup':
            # initial subscription
            self.subscr_signup(data)
        elif data['txn_type'] == 'subscr_payment':
            # subscription renewed
            self.subscr_payment(data)
        elif data['txn_type'] == 'subscr_modify':
            # subscription plan modified
            self.subscr_modify(data)
        elif data['txn_type'] == 'subscr_eot':
            # subscription expired
            self.subscr_eot(data)
        elif data['txn_type'] == 'subscr_cancel':
            # subscription canceled
            self.subscr_cancel(data)
        elif data['txn_type'] == 'subscr_failed':
            # subscription failed
            self.subscr_failed(data)

        return
 def storeQueryInDB(self, qObj):
     ''' To do:
     Parse parameters of query from the received msg and store it in DB
     '''
     foundFlag = False
     try:
         uname = User.get(User.username==str(self.qMessage['from']).split("@")[0])
         foundFlag = True
     except User.DoesNotExist:
         print "User not in DB"
         return False
     
     qResults = Query.select().where(Query.queryNo==str(qObj['queryNo'])).count()
     if(qResults!=0):
         print 'Discarding message for queryNo: ' + str(qObj['queryNo']) + ' as it already existed in DB'
         return False
     
     if foundFlag:
         q = Query()
         q.username = uname
         q.queryNo = str(qObj['queryNo'])
         q.dataReqd = str(qObj['dataReqd'])
         if 'frequency' in qObj:
             q.frequency = eval(str(qObj['frequency']))
         else:
             q.frequency = 0
         if 'latitude' in qObj:
             q.Latitude = eval(str(qObj['latitude']))
         else:
             q.Latitude = -1.0
         if 'longitude' in qObj:
             q.Longitude = eval(str(qObj['longitude']))
         else:
             q.Longitude = -1.0
         q.fromTime = datetime.datetime.fromtimestamp(eval(str(qObj['fromTime']))/1000)
         q.toTime = datetime.datetime.fromtimestamp(eval(str(qObj['toTime']))/1000)
         q.expiryTime = datetime.datetime.fromtimestamp(eval(str(qObj['expiryTime']))/1000)
         q.Location = 'hardcoded'#str(qObj['location'])
         if 'activity' in qObj:
             q.Activity = str(qObj['activity'])
         else:
             q.Activity = "Don't Care"
         q.countMin = eval(str(qObj['countMin']))
         q.countMax = eval(str(qObj['countMax']))
         q.countReceived = 0
         if 'radius' in qObj:
             q.Radius = eval(str(qObj['radius']))
         else:
             q.Radius = -1
         
         q.save()    
         self.queryDBObject = q
                
         if(self.queryPossible()):
             self.sendAcknowledgement(True)
             return True
         else:
             self.sendAcknowledgement(False)
             return False
Ejemplo n.º 29
0
def block_user(username, user, session):

    target = User.find(username=username)
    if not user:
        abort(404)

    user.block(target)
    return response({'blocked': True})
Ejemplo n.º 30
0
 def show(self, user=None):
     self.executerQuery = ExecuterQueryService.ExecuterQueryService()
     self.currentUser = User.User(user)
     self.userNameLabel.setText(self.currentUser.login)
     self.setDelegatesTableView()
     self.editMenuList()
     self.giveUserRights()
     QtWidgets.QMainWindow.show(self)
Ejemplo n.º 31
0
class UserFromSession():
    """Take the session, get the user key, and return the user object.
    If no user if set yet, create a new user, store in datastore, set cookie, and return that user"""
    user = None;
    
    def __init__(self, session):
        user_key = session.get('user_key')
        if user_key:
            self.user = db.get(db.Key(user_key))
        if not self.user:
            # No user key stored - make a new one
            self.user = User();
            self.user.put()
            session['user_key'] = str(self.user.key())
            
    def get_user(self):
        return self.user
Ejemplo n.º 32
0
def message(public_id):

    user = User.get_by_public_id(public_id)
    print(user)
    if not user:
        return abort(404)

    return render_template('message.html', user=user)
Ejemplo n.º 33
0
 def __init__(self, session):
     user_key = session.get('user_key')
     if user_key:
         self.user = db.get(db.Key(user_key))
     if not self.user:
         # No user key stored - make a new one
         self.user = User();
         self.user.put()
         session['user_key'] = str(self.user.key())
Ejemplo n.º 34
0
 def make_move(self, board_num, cell, user):
     """Get a move. If it's legal update the game state, save it, and send it to the client."""
     if self.game.move(board_num, cell, user):
         self.game.put() # Save the game state
         self.send_update() # Send it to the client
     if self.game.userO == User.get_by_id(AI_ID): # Check if player O is AI - need to fix the check
         board_num, cell = Ai.nextMove(self.game)
         if self.game.move(board_num, cell, self.game.userO):
             self.game.put()
             self.send_update()
Ejemplo n.º 35
0
    def current_user(self):
        if self.session.get("user"):
            # User is logged in
            return self.session.get("user")
        else:
            # Either used just logged in or just saw the first page
            # We'll see here
            cookie = facebook.get_user_from_cookie(self.request.cookies,
                                                   FACEBOOK_APP_ID,
                                                   FACEBOOK_APP_SECRET)
            if cookie:
                # Okay so user logged in.
                # Now, check to see if existing user
                user = User.get_by_key_name(cookie["uid"])
                if not user:
                    # Not an existing user so get user info
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    loc = profile["location"]
                    loc_id = loc["id"]
                    city = graph.get_object(loc_id)

                    user = User(
                        key_name=str(profile["id"]),
                        id=str(profile["id"]),
                        name=profile["name"],
                        profile_url=profile["link"],
                        access_token=cookie["access_token"],
                        city = city["name"]
                    )
                    print user.access_token
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    user.access_token = cookie["access_token"]
                    user.put()
                # User is now logged in
                self.session["user"] = dict(
                    name=user.name,
                    profile_url=user.profile_url,
                    id=user.id,
                    access_token=user.access_token
                )
                return self.session.get("user")
        return None
 def processMessage(self, msg):
     ''' The msg object is actually the raw XMPP message object. Parse it yourself!'''
     newMsg = json.loads(msg['body'])
     if str(msg['subject'])=='ProviderResponse':
         ''' This is a message which gives the response of some provider which we flooded for query results! '''
         if(str(newMsg['status'])=='Accepted'):
             #Party! Request accepted!
                 
             u = User.get(User.username==str(msg['from']).split("@")[0])
             
             if(self.currentCount >= eval(str(self.queryObject['countMin']))):
                 #We don't need this guy anymore. Send him a not required message.
                 self.sendProviderConfirmation(u, False)
                 return
             
             self.usersServicing += [u]
             self.currentCount += 1
             
             self.sendProviderConfirmation(u, True)
             
             if(self.currentCount >= eval(str(self.queryObject['countMin']))):
                 #Send final confirmation to client!
                 self.waiting = True
                 self.sendFinalConfirmation(True)
                 
                 ''' Set Timeout for query expiry time! '''
     
                 #Check for bad query expiry times! 
                 if self.queryDBObject.expiryTime < datetime.datetime.now():
                     '''Bad time. Set query expiry time to be toTime-now() + 60 seconds'''
                     toSet = (self.queryDBObject.toTime - datetime.datetime.now()).total_seconds() + 60
                     if(toSet <= 20):
                         #Something is really bad. Just set expiry time out to 4 minutes and pray its all good.
                         toSet = 240.0
                 else:
                     toSet = (self.queryDBObject.expiryTime - datetime.datetime.now()).total_seconds() + 60
                     if(toSet <= 20):
                         #Something is really bad. Just set expiry time out to 4 minutes and pray its all good.
                         toSet = 240.0
                         
                 ''' Set expiry timeout'''
                 print 'Setting data collection timeout for queryNo: ' + self.queryNo + ' for ' + str(toSet) + ' seconds'
                 threading.Timer(toSet, self.putDataCollectionTimeoutOnThread).start()
                 
         else:
             #Snobby client, rejected our request. Ignore this guy!
             pass
     elif str(msg['subject'])=='Data':
         ''' This is a message which somehow provides the final data given by the provider! We're nearly done now.'''
         ''' UPDATE - The data provided is in the form of a JSON message. Parse it and store it in our response message! '''
         curCount = self.finalDataPackage['noOfFiles']
         curCount += 1
         self.finalDataPackage['sensorData' + str(curCount)] = newMsg['sensorData']
         self.finalDataPackage['noOfFiles'] = curCount
         self.receivedCount += 1
         if(curCount >= self.currentCount):
             'We are done now! Send the data back to the requester and be done with life now!'
             msgToSend = str(json.dumps(self.finalDataPackage))
             self.msgHandler.send_message(mto=self.qMessage['from'], mbody=msgToSend, msubject='RequestedData')
             
             ''' Time to die! '''
             self.amIDone = True
             pass
     else:
         print 'Got unrecognized message for queryNo: ' + str(self.queryNo) + '. Message subject: ' + str(msg['subject'])
Ejemplo n.º 37
0
def query_all():
    users = User.query()
    for user in users:
        print(user)
Ejemplo n.º 38
0
def save():
    user = User(2, 'zhang')
    user.save()
Ejemplo n.º 39
0
def index(request):
    users = yield from User.findAll()
    return {
        '__template__' : 'test.html',
        'users': users
    }
 def registerUser(self, msgObject, userName): #(long userID,long password, string[] sensorsPresent): #msg contains userid+capabilities 
     ''' To do:
         Parse the incoming message and store the capabilities of a particular user in the DB
     '''
     print "Inside RegisterUser"
     foundFlag = False
     try:
         u = User.get(User.username==userName)
         foundFlag = True
     except User.DoesNotExist:
         if str(msgObject['ActivityRecognition'])=='present':
             activity = True
         else:
             activity = False
         if str(msgObject['DownloadAllowed'])=='yes':
             download = True
         else:
             download = False
         if 'Location' in msgObject:
             lAr = msgObject['Location']
             location = str(lAr[0])
             latitude = str(lAr[1])
             longitude = str(lAr[2])
         else:
             location = 'Hardcoded'
             latitude = 0.0
             longitude = 0.0
         u = User(username=str(userName), RegistrationDate=datetime.datetime.now(), ActivityRecognition=activity, DownloadAllowed=download, Location=location, Latitude=latitude, Longitude=longitude)
         u.save()
     #print "User Saved"
     
     '''Update location anyways, if the key is present '''
     if 'Location' in msgObject:
         lAr = msgObject['Location']
         location = str(lAr[0])
         latitude = str(lAr[1])
         longitude = str(lAr[2])
         u.Longitude = longitude
         u.Latitude = latitude
         u.Location = location
         u.save()
             
     
     if foundFlag:
         #User already exists. Should handle it differently.
         #Means it could be a updation message. Delete all his previous Sensor Relation entries and fill new ones for now.
         print "User already existed! Deleting previous relation entries!"
         surtoD = SensorUserRel.select().where(SensorUserRel.user==u)
         for s in surtoD:
             s.delete_instance()
                 
     
     sensorQueue = []
     numSensor = eval(str(msgObject['noSensors']))
     for i in range(1, numSensor+1):
         ''' TODO: Check for fields to be empty before parsing them with eval! '''
         sName = "sensor" + str(i)
         try:
             s = Sensor.get(Sensor.SensorType==str(msgObject[sName][0]), Sensor.maxRange==eval(str(msgObject[sName][1])), Sensor.minDelay==eval(str(msgObject[sName][2])), Sensor.power==eval(str(msgObject[sName][3])), Sensor.resolution==eval(str(msgObject[sName][4])))
         except Sensor.DoesNotExist:
             s = Sensor(name="temp", SensorType=str(msgObject[sName][0]), maxRange=eval(str(msgObject[sName][1])), minDelay = eval(str(msgObject[sName][2])), power = eval(str(msgObject[sName][3])), resolution=eval(str(msgObject[sName][4])))
             s.save()
         sensorQueue += [s]
         
         
     for s in sensorQueue:
         sur = SensorUserRel(user=u, sensor=s)
         sur.save()     
             
     print "Registered" + str(userName) + " Successfully!"
     
     self.msgHandler.send_message(mto=str(self.rMessage['from']).split("/")[0], msubject="Registration Successful!", mbody="Thank you! Registration/Updation Successful!")
     
     return