def create_1000_users_in_Parse():

    li_u = []

    for i in range(1000):
        u = _User()
        li_u.append(u)

    register_for_events(li_u)

    for u in li_u:

        User.signup( username = u.username, password = "******", 
            u_num = u.u_num,
            sex = u.sex,
            age = u.age,
            eyes = u.eyes,
            dob = u.dob,
            full_name = u.full_name,
            first_name = u.first_name,
            last_name = u.last_name,
            college = u.college,
            email_address = u.email_address,
            li_events_registered = u.li_events_registered)

        print "User {} signed up.".format(u.u_num)


    # batcher = ParseBatcher()
    # batcher.batch_save(li_u)

    pass
Ejemplo n.º 2
0
  def test_today_pings(self):
    assignTask = Function("assignTask")
    ping = Function("ping")
    u1 = User.login('redsox55', 'secure123')
    assignee = User.Query.get(username='******')
    with SessionToken(u1.sessionToken):
      title = 'serha34g444'
      response = assignTask(
        title=title,
        description="Send a ping to this task",
        watchers=[u[2] for u in sample_users],
        score=2,
        assignee=assignee.email,
      )
    self.assertIn('task', response['result'])

    todayPings = Function('todayPings')
    with SessionToken(u1.sessionToken):
      task = Task.Query.get(title=title)
      ping(taskId=task.objectId)
      todayPingsU1 = todayPings()
    print "TODAY PINGS U1: %s" % todayPingsU1
    self.assertEqual(len(todayPingsU1['result']), 1)

    u2 = User.login('baracky', 'usanumber1')
    with SessionToken(u2.sessionToken):
      ping(taskId=task.objectId)
      ping(taskId=task.objectId)
      todayPingsU2 = todayPings()
    print "TODAY PINGS U2: %s" % todayPingsU2
    self.assertEqual(len(todayPingsU2['result']), 2)
Ejemplo n.º 3
0
 def GET(self, request):
     email = request.values.get("email").lower()
     User.request_password_reset(
         email=email
     )
     
     return flask.redirect('/')
Ejemplo n.º 4
0
 def PUT(self, request, post_id):
     story = models.story.Story.active_story()
     if not story:
         return ("", 400)
     elif not story.accepting_snippets():
         return ("", 429)
         
     post = models.post.Post.get(post_id)
     if not post:
         return ("", 404)
         
     voted_users = [user['objectId'] for user in post.voted_users]
     if User.current_user().objectId not in voted_users:
         post.voted_users.append(User.current_user())
     
     post.save()
     
     refresh = False
     if len(post.voted_users) >= models.post.Post.max_vote_count():
         story.accept_post(post)
         story.save()
         
         refresh = True
     
     return json.dumps({
         'votes': len(post.voted_users),
         'refresh': refresh
     })
Ejemplo n.º 5
0
def Login(userIDClass):
    global username, userDetails
    username = usernameEntry.get()
    password = passwordEntry.get()
    myClassName = 'User'
    myClass = Object.factory(myClassName)
    username = str(username.lower())
    Id = userDetails[username]
    print(Id)
    data = myClass.Query.get(objectId = Id)
    teacher = data.teacher
    print(teacher)
    if username in userDetails:
        print('Logging in')
        try:
            User.login(username, password)
            print('Logged in')
            currentUserLabel.config(text = 'Logged in as '+username+'. Class: '+userIDClass[Id])
            if teacher == False:
                outputUserResults()
                newWordButton.config(state = DISABLED)
                quizSelectButton.config(state = NORMAL)
            else:
                newWordButton.config(state = NORMAL)
                quizSelectButton.config(state = DISABLED)
                resultsList.delete(0, END)
                findTeachersPupils(Id)
        except:
            print('Incorrect password')
            currentUserLabel.config(text = 'Incorrect password')
    else:
        currentUserLabel.config(text = 'That is an invalid username')
        print('That is an invalid username')
    print('FUNCTION: userLogin COMPLETE')
    print(time.asctime( time.localtime(time.time()) ))
Ejemplo n.º 6
0
    def PUT(self, request, post_id):
        story = models.story.Story.active_story()
        if not story:
            return ("", 400)
        elif not story.accepting_snippets():
            return ("", 429)

        post = models.post.Post.get(post_id)
        if not post:
            return ("", 404)

        voted_users = [user['objectId'] for user in post.voted_users]
        if User.current_user().objectId not in voted_users:
            post.voted_users.append(User.current_user())

        post.save()

        refresh = False
        if len(post.voted_users) >= models.post.Post.max_vote_count():
            story.accept_post(post)
            story.save()

            refresh = True

        return json.dumps({'votes': len(post.voted_users), 'refresh': refresh})
Ejemplo n.º 7
0
def signUp(names, classNames):
    global username
    username = usernameEntry.get()
    password = passwordEntry.get()
    username = username.lower()
    value = classBox.curselection()
    strip = str(value).strip(',')
    value = int(strip[1])
    group = classNames[value]
    if username in str(names):
        currentUserLabel.config(text = 'That username is already taken')
        print('That username is already taken')
    else:
        teacher = teacherVar.get()
        if teacher == 0:
            u = User.signup(username, password, teacher = False, group = group)
            currentUserLabel.config(text = 'Logged in as '+username)
            addUsertoResults()
            outputUserResults()
            newWordButton.config(state = DISABLED)
            quizSelectButton.config(state = NORMAL)
            print('Account Created')
        else:
            u = User.signup(username, password, teacher = True, group = group)
            currentUserLabel.config(text = 'Logged in as '+username)
            newWordButton.config(state = NORMAL)
            quizSelectButton.config(state = DISABLED)
            resultsList.delete(0, END)
            print('Account Created')
    print('FUNCTION: signUp COMPLETE')
    print(time.asctime( time.localtime(time.time()) ))
Ejemplo n.º 8
0
	def login_twitter(self, details):
		if not User.Query.filter(username=details['screen_name']):
			print "hello"
			User.signup(
				username=details['screen_name'], 
				password='******',
				NAME=details['name'],
				# cover=details['profile_background_image_url_https'],
				# image=details['profile_image_url']
			)
		else:
			pass
Ejemplo n.º 9
0
    def testCanGetCurrentUser(self):
        user = User.signup(self.username, self.password)
        self.assertIsNotNone(user.sessionToken)

        register(getattr(settings_local, 'APPLICATION_ID'),
                 getattr(settings_local, 'REST_API_KEY'),
                 session_token=user.sessionToken)

        current_user = User.current_user()
        self.assertIsNotNone(current_user)
        self.assertEqual(current_user.sessionToken, user.sessionToken)
        self.assertEqual(current_user.username, user.username)
Ejemplo n.º 10
0
def index():
 	settings_local.initParse()
	if request.method == 'POST' and request.form["what"]== 'Login':
		try:
			print request.form["password"]
			u = User.login(request.form["username"],request.form["password"])
			session['session_token'] = u.sessionToken
			resp = make_response(render_template("index.html"))
			return resp
		except:
			return render_template('login.html',error="Invalid username or password")
	elif request.method == 'POST' and request.form["what"]=='SignUp':
		email = request.form["email"]
		password = request.form["password"]
		ninja = request.form["ninja"]
		birthdate = request.form["birthdate"]
		u = User.signup(email,password)
		u.email=email
		u.save()
		# proPic.save(os.path.join(app.config['UPLOAD_FOLDER']),"userdp.png")
		# connection = httplib.HTTPSConnection('api.parse.com', 443)
		# connection.connect()
		# connection.request('POST', '/1/files/profilePic.png', open('userdp.png', 'rb').read(), {
		# "X-Parse-Application-Id": "${Y4Txek5e5lKnGzkArbcNMVKqMHyaTk3XR6COOpg4}",
		# "X-Parse-REST-API-Key": "${nJOJNtVr1EvNiyjo6F6M8zfiUdzv8lPx31FBHiwO}",
		# "Content-Type": "image/png"
		# })
		# result = json.loads(connection.getresponse().read())
		# print result
		# connection.request('POST', '/1/classes/_User', json.dumps({
		# "username": email,
		# "picture": {
		#  "name": "profilePic.png",
		#  "__type": "File"
		# }
		# }), {
		# "X-Parse-Application-Id": "${Y4Txek5e5lKnGzkArbcNMVKqMHyaTk3XR6COOpg4}",
		# "X-Parse-REST-API-Key": "${nJOJNtVr1EvNiyjo6F6M8zfiUdzv8lPx31FBHiwO}",
		# "Content-Type": "application/json"
		# })
		# result = json.loads(connection.getresponse().read())
		# print result
		session['session_token'] = u.sessionToken
		resp = make_response(render_template("index.html"))
		return u.sessionToken
	else:
		if session.get('session_token') is None:
			print "nohhh"
			return render_template('login.html')
		else:
			print "yes"
			return render_template('index.html')
Ejemplo n.º 11
0
def sign_up():
    while True:
        try:
            sign_up_dict = get_data()
            current_user = User.signup(sign_up_dict["username"], sign_up_dict["password"], email=sign_up_dict["email"],
                                       Experience=sign_up_dict["exp"], Name=sign_up_dict["name"],
                                       Profession=sign_up_dict["profession"])
            break
        except ResourceRequestBadRequest:
            print("E-mail or username already exist")
        except ValueError:
            print("Invalid exp value")
    current_user = User.login(sign_up_dict["username"], sign_up_dict["password"])
    return current_user
Ejemplo n.º 12
0
    def testCanGetCurrentUser(self):
        user = User.signup(self.username, self.password)
        self.assertIsNotNone(user.sessionToken)

        register(
            getattr(settings_local, 'APPLICATION_ID'),
            getattr(settings_local, 'REST_API_KEY'),
            session_token=user.sessionToken
        )

        current_user = User.current_user()
        self.assertIsNotNone(current_user)
        self.assertEqual(current_user.sessionToken, user.sessionToken)
        self.assertEqual(current_user.username, user.username)
Ejemplo n.º 13
0
def parse_login(email, password):	
	
	email = email.lower()

	try:
		user = get_parse_user_by_email(email)
	except:
		return {'error': "No one has signed up with this address."}
	
	# only check for verified addresses on users who signed up after initializing email verification
	try:
		if user.emailVerified == False:
			return {'error': "Email address not verified. Please check inbox."}
	except:
		pass

	u = ParseUser.login(email, password)
	header = u.session_header()
	
	response = {'token': header['X-Parse-Session-Token'],
				}
				#'chargify_active': u.chargify_active,
				#'active': u.active,
				#'user': u,
	
	try:
		response['ref'] = u.ref
		response['staff'] = False
	except:
		response['ref'] = None
		response['staff'] = True
		
	return response
Ejemplo n.º 14
0
def create_parse_user(email, referred_by=None):
	
	email = email.lower()

	try:	
		if LIVE:
			user_type = "live"
		else:
			user_type = "test"
		ref = gen_alphanum_key()
		user = User.signup(email, "pass", email=email, type=user_type, ref=ref, welcomed=False)	
	
	except Exception as err:
		return {'error': ast.literal_eval(err[0])['error']}
	
	if LIVE:
		try:
			highrise_id = create_highrise_account(email, 'user')
			user.highrise_id = highrise_id
			user.save()
		except:
			pass

	if referred_by:
		try:
			referral = Referrals(email=email, code=referred_by, verified=False)
			referral.save()
		except Exception as err:
			return {'error': ast.literal_eval(err[0])['error']}	
	
	return {'created': True, 'ref': ref}
Ejemplo n.º 15
0
 def GET(self, request, story_id):        
     story = models.story.Story.get(story_id)
     if not story:
         story = models.story.Story.active_story()
         
     accepted_posts = sorted([
         models.post.Post.get(post['objectId'])
         for post in story.accepted_posts
     ], cmp=lambda x, y: 1 if x.createdAt > y.createdAt else -1)
     
     snippets = sorted([
         models.post.Post.get(post['objectId'])
         for post in story.snippets
     ], cmp=models.post.comparePosts)
     
     initials = ":)"
     if self.session(request):
         with SessionToken(self.session(request)):
             user = User.current_user()
             initials = user.first_name[0] + user.last_name[0]
     
     return flask.render_template(
         "story.html",
         story=story,
         accepted_posts=accepted_posts,
         snippets=snippets,
         
         initials = initials,
         session = self.session(request),
         
         max_vote_count=models.post.Post.max_vote_count(),
         user_voted_story=story.user_voted(self.session(request)),
         
         text_length=models.post.Post.text_length
     )
Ejemplo n.º 16
0
def delete_sample_users():
  for username, password, email in sample_users:
    try:
      u = User.login(username, password)
      u.delete()
    except:
      pass
Ejemplo n.º 17
0
  def test_create_task(self):
    assignTask = Function("assignTask")

    assignee = User.Query.get(username='******')
    u = User.login('redsox55', 'secure123')
    with SessionToken(u.sessionToken):
      title = 'w45h45r4g4h'
      response = assignTask(
        title=title,
        description="See title",
        watchers=[user[2] for user in sample_users],
        email=None,
        assignee=assignee.email,
      )
    self.assertIn('task', response['result'])

    tasks = Task.Query.all()
    self.assertEqual(len(tasks), 1)
    t = tasks[0]
    self.assertEqual(t.title, title)
    self.assertEqual(t.creator.objectId, u.objectId)
    self.assertEqual(t.score, 0)
    self.assertEqual(len(t.watchers), len(sample_users))
    self.assertEqual(t.assignee.objectId, assignee.objectId)

    self.assertTrue(all(w["className"] == '_User' for w in t.watchers))
Ejemplo n.º 18
0
def register():
    username = request.form['username']
    password = request.form['password']
    email = request.form['email']
    u = User.signup(username, password, email=email)
    circle = Circle(name="all", owner=u, users=[u])
    circle.save()
    u.circles = [circle]
    u.postingTo = ['all']
    u.save()

    session['username'] = username
    session['password'] = password
    u = User.login(username, password)
    u.save()
    return redirect(url_for('index'))
Ejemplo n.º 19
0
def dashboard():
    u = User.login("arjun", "password")
    fname = u.fname
    lname = u.lname
    username = u.username

    name = fname + " " + lname
    email=u.email
    zipcode = u.zipcode
    state = u.state
    address = u.streetAddress
    city = u.city

#     monthly = getMonthlyRates("arjun")
#     cost = monthly["cost"]
#     cost = round(cost, 2)
#     split = monthly["split"]
#
#     water = split["water"]
#     gas = split["gas"]
#     electric = split["electric"]

    water = 57.39
    electric = 139.16
    gas = 140.74
    cost = 337


    billDue = dueDate().strftime("%A, %B %d")
    return render_template('dashboard.html', dueDate=billDue, name=name, email=email, city=city, address=address, state=state, zipcode=zipcode, cost=cost, water=water, gas=gas, electric=electric)
Ejemplo n.º 20
0
def circles():
    if 'username' in session:
        username = escape(session['username'])
        password = escape(session['password'])
        user = User.login(username, password)
        if request.method == 'POST':
            circle = Circle(name=request.form['name'])
            circle.users = [user]
            circle.owner = user
            user.circles.append(circle)
            circle.save()
            user.save()
            return redirect(url_for('circles'))
        req = Request.Query.filter(toUser=username)
        friends = []
        circles = []
        for c in user.circles:
            circle = Circle.Query.get(objectId=c.get('objectId'))
            circles.append(circle)
            if circle.name == 'all':
                for u in circle.users:
                    friend = User.Query.get(objectId=u.get('objectId'))
                    if friend.objectId != user.objectId:
                        friends.append(friend)
        return render_template('circles.html', user=user, req=req, friends=friends, circles=circles)
    else:
        return render_template('signup.html')
Ejemplo n.º 21
0
def test():
    u = User.login("arjun", "password")

#     print predictBills(6, 'arjun')
    print getMonthlyRates("arjun")

    return render_template('test.html', u="blah")
Ejemplo n.º 22
0
def makePayment():
    req = request.get_json()

    if req is None:
        return json.dumps({"status": "fail",
                "reason": "Must include JSON."})

    # TODO authentication to make sure this user
    #      has permission to do this
    if not 'username' in req or not 'password' in req:
        return json.dumps({"status": "fail",
                "reason": "Must include username and password."})

    if not 'amount' in req:
        return json.dumps({"status": "fail",
                "reason": "Must include payment amount."})

    # make sure we can validate to the db
    try:
        u = User.login(req['username'], req['password'])
    except:
        return json.dumps({"status": "fail",
                "reason": "Unable to log user in."})

    # attempt the payment
    res = achCharge(float(req['amount']), u.routingNo, u.acctNo)
    if res['CmdStatus'] != 'Approved':
        return json.dumps({"status": "fail",
                "reason": "Unable to charge account."})

    u.acctBalance += float(req['amount'])
    u.save()
    return json.dumps({"status":"success"})
Ejemplo n.º 23
0
    def GET(self, request, story_id):
        story = models.story.Story.get(story_id)
        if not story:
            story = models.story.Story.active_story()

        accepted_posts = sorted([
            models.post.Post.get(post['objectId'])
            for post in story.accepted_posts
        ],
                                cmp=lambda x, y: 1
                                if x.createdAt > y.createdAt else -1)

        snippets = sorted([
            models.post.Post.get(post['objectId']) for post in story.snippets
        ],
                          cmp=models.post.comparePosts)

        initials = ":)"
        if self.session(request):
            with SessionToken(self.session(request)):
                user = User.current_user()
                initials = user.first_name[0] + user.last_name[0]

        return flask.render_template(
            "story.html",
            story=story,
            accepted_posts=accepted_posts,
            snippets=snippets,
            initials=initials,
            session=self.session(request),
            max_vote_count=models.post.Post.max_vote_count(),
            user_voted_story=story.user_voted(self.session(request)),
            text_length=models.post.Post.text_length)
Ejemplo n.º 24
0
    def on_jugar(self):

        print "ON_JUGAR"

        if app.root.user == None:
            nick = "nobody" + str(len(User.Query.all())).zfill(4)
            app.root.user = User.signup(nick, "012345679", nickname=nick)
        else:
            nick = app.root.user.nickname

        app.root.remove_widget(app.root.lobby)

        #crear selector de juego
        app.root.games = GameSelector()
        app.root.add_widget(app.root.games)

        app.root.gamelist = Partidas.Query.all().order_by("-createdAt")

        #games list
        for i in app.root.gamelist:
            game = GameItem()


            game.by.text = i.Creator.nickname
            game.gametag.text = i.Gametag


            if i.Creator.nickname == nick:
                game.btn_action.text = "Cancel game"

            app.root.games.gamelist.add_widget(game)
Ejemplo n.º 25
0
def user_calleft(token):
    if request.method == 'GET':
        session_token  = token
        with SessionToken(session_token):
            me = User.current_user()
            me.calleft = user_calories(token) - me.feed['calories']
            me.save()
            return me.calleft
Ejemplo n.º 26
0
def user_calories(token):
    if request.method == 'GET':
        session_token  = token
        with SessionToken(session_token):
            me = User.current_user()
            me.calories = str(float(me.weight) * 33 )
            me.save()
            return me.calories
Ejemplo n.º 27
0
def user_register():
    if request.method == 'POST':
        user_name = request.form['user']
        password  = request.form['password']
        phone     = request.form['phone']
        weight    = request.form['weight']
        u = User.signup(user_name, password, phone=phone, weight=weight)
        return jsonify(result='Registered!')
Ejemplo n.º 28
0
def user_calories(token):
    if request.method == 'GET':
        session_token = token
        with SessionToken(session_token):
            me = User.current_user()
            me.calories = str(float(me.weight) * 33)
            me.save()
            return me.calories
Ejemplo n.º 29
0
def user_register():
    if request.method == 'POST':
        user_name = request.form['user']
        password = request.form['password']
        phone = request.form['phone']
        weight = request.form['weight']
        u = User.signup(user_name, password, phone=phone, weight=weight)
        return jsonify(result='Registered!')
Ejemplo n.º 30
0
    def POST(self, request):
        username = request.values.get("email").lower()
        password = request.values.get("password")

        try:
            user = User.signup(username,
                               password,
                               email=username,
                               first_name=request.values.get("first_name"),
                               last_name=request.values.get("last_name"))
        except ResourceRequestBadRequest:
            user = User.login(username, password)

        response = flask.make_response(flask.redirect("/"))

        response.set_cookie("session", user.sessionToken)
        return response
Ejemplo n.º 31
0
def user_calleft(token):
    if request.method == 'GET':
        session_token = token
        with SessionToken(session_token):
            me = User.current_user()
            me.calleft = user_calories(token) - me.feed['calories']
            me.save()
            return me.calleft
Ejemplo n.º 32
0
def login():
	if request.method == 'POST':
		user_name = request.form['user']
		password  = request.form['password']

	u = User.login(user_name, password)
	session["auth_token"] = u.sessionToken
	session["user_namFriende"] = u.username
Ejemplo n.º 33
0
def signup(username, password):
    try:
        u = User.signup(username, password)
        sc = ShoppingCart(cartItems=[])
        sc.save()
        u.shoppingCart = sc
        u.save()
    except:
        return "User Already Exists"
    return u
Ejemplo n.º 34
0
 def signup_button(self):
     try:
         u = User.signup(self.username.text, self.password.text)
         u.displayName = u.username
         u.save()
         self.error.text = "User created successfully. Please Login."
         self.error.color = [0,1,0,1]
     except ParseError:
         self.error.text = "Signup Failed. Choose another username."
         self.error.color = [1,0,0,1]
Ejemplo n.º 35
0
 def testToNative(self):
     ptr = Pointer(GameScore(objectId='xyz'))
     self.assertEqual(
         ptr._to_native(),
         dict(__type='Pointer', className='GameScore', objectId='xyz'))
     ptr = Pointer(
         User(objectId='dh56yz', username="******"))
     self.assertEqual(
         ptr._to_native(),
         dict(__type='Pointer', className='_User', objectId='dh56yz'))
Ejemplo n.º 36
0
def signup(username, password):
    try:
        u = User.signup(username, password)
        sc = ShoppingCart(cartItems=[])
        sc.save()
        u.shoppingCart = sc
        u.save()
    except:
        return "User Already Exists"
    return u
Ejemplo n.º 37
0
 def login_button(self):
     try:
         u = User.login(self.username.text, self.password.text)
         app = kivy.app.App.get_running_app()
         app.user = u
         if not self.manager.has_screen('home'):
             self.manager.add_widget(HomeScreen(name='home'))
         self.manager.current = 'home'
     except ParseError:
         self.error.text = "Login Failed. Try again."
         self.error.color = [1,0,0,1]
Ejemplo n.º 38
0
def fakeNewRunFromCSV(csvLines, updateFrequency, length, objID, username, pwd,
                      delay):
    '''
    use like this...
    fakeNewLocations(runnerLocations, 1, 40)
    runnerLocations is the query,
    1 is going to send the next location every 1 second,
     and will do this for 40 seconds
    '''
    sleep(delay)
    u = User.login(username, pwd)
    updateNum = 0
    for line in csvLines[1:]:
        lat, lon, time, username, user_objid, dist, runT, speed = line.strip(
        ).split(",")
        rl = RunnerLocations(location=GeoPoint(latitude=float(lat),
                                               longitude=float(lon)),
                             time=datetime.datetime.now(),
                             user=u,
                             distance=float(dist),
                             duration=runT,
                             speed=float(speed))
        rl.save()

        base_url = 'https://crowdcheerdb.herokuapp.com/parse/classes/CurrRunnerLocation/' + objID
        header = {
            'X-Parse-Application-Id':
            'QXRTROGsVaRn4a3kw4gaFnHGNOsZxXoZ8ULxwZmf',
            'Content-type': 'application/json'
        }
        data = {
            "speed": float(speed),
            "duration": runT,
            "distance": float(dist),
            "location": {
                "__type": "GeoPoint",
                "latitude": float(lat),
                "longitude": float(lon)
            },
            "time": {
                "__type": "Date",
                "iso": datetime.datetime.utcnow().isoformat()
            }
        }
        resp = requests.put(base_url, headers=header, data=json.dumps(data))
        print resp.json()
        print "updated %s times" % updateNum
        print "location : %s, lat : %s, lon : %s" % (rl.location, lat, lon)
        print "speed : %s , distance : %s , duration : %s" % (
            rl.speed, rl.distance, rl.duration)
        updateNum += 1
        if (updateNum > length):
            break
        sleep(updateFrequency)
Ejemplo n.º 39
0
    def DELETE(self, request, post_id):
        story = models.story.Story.active_story()
        if not story:
            return ("", 400)
        elif not story.accepting_snippets():
            return ("", 429)

        post = models.post.Post.get(post_id)
        if not post:
            return ("", 404)

        voted_users = [user['objectId'] for user in post.voted_users]
        if User.current_user().objectId in voted_users:
            post.voted_users = [
                user for user in post.voted_users
                if user['objectId'] != User.current_user().objectId
            ]

        post.save()
        return json.dumps({'votes': len(post.voted_users)})
Ejemplo n.º 40
0
    def setUp(self):
        self.username = TestUser.USERNAME
        self.password = TestUser.PASSWORD
        self.game = None

        try:
            u = User.login(self.USERNAME, self.PASSWORD)
        except ResourceRequestNotFound:
            # if the user doesn't exist, that's fine
            return
        u.delete()
Ejemplo n.º 41
0
    def setUp(self):
        self.username = TestUser.USERNAME
        self.password = TestUser.PASSWORD
        self.game = None

        try:
            u = User.login(self.USERNAME, self.PASSWORD)
        except ResourceRequestNotFound:
            # if the user doesn't exist, that's fine
            return
        u.delete()
Ejemplo n.º 42
0
    def user_voted(self, session):
        with SessionToken(session):
            for snippet in self.snippets:
                post = Post.get(snippet['objectId'])
                user_voted = bool([
                    user for user in post.voted_users
                    if user['objectId'] == User.current_user().objectId
                ])

                if user_voted:
                    return True
            return False
Ejemplo n.º 43
0
 def user_voted(self, session):
     with SessionToken(session):
         for snippet in self.snippets:
             post = Post.get(snippet['objectId'])
             user_voted = bool([
                 user for user in post.voted_users
                 if user['objectId'] == User.current_user().objectId
             ])
             
             if user_voted:
                 return True
         return False
Ejemplo n.º 44
0
def login():
    if session.get("logged_in"):
        return redirect(url_for("list_projects"))
    if request.method == "POST":
        try:
            u = User.login(request.form["username"], request.form["password"])
            session["logged_in"] = True
            session["uid"] = u.objectId
        except:
            flash("bad login")

    return render_template("login.html")
Ejemplo n.º 45
0
	def logIn(self):
		"""Attempts to log in the user with the given credentials by checking if the user exits within the database"""
		try:
			self.user = User.login(self.logInCredentials['userID'], self.logInCredentials['password'])
			self.token = self.user.sessionToken
			self.full_name = self.user.full_name
			self.logInSuccessful = True
			print("\nLogged in successfully!\n")
		except:
			self.logInSuccessful = False
			print("\nAuthorization Failed.\n")
			time.sleep(1)
		return self.logInSuccessful
Ejemplo n.º 46
0
 def DELETE(self, request, post_id):
     story = models.story.Story.active_story()
     if not story:
         return ("", 400)
     elif not story.accepting_snippets():
         return ("", 429)
         
     post = models.post.Post.get(post_id)
     if not post:
         return ("", 404)
         
     voted_users = [user['objectId'] for user in post.voted_users]
     if User.current_user().objectId in voted_users:
         post.voted_users = [
             user for user in post.voted_users
             if user['objectId'] != User.current_user().objectId
         ]
     
     post.save()
     return json.dumps({
         'votes': len(post.voted_users)
     })
Ejemplo n.º 47
0
def user_feed(token):
    if request.method == 'GET':
        session_token = token
        with SessionToken(session_token):
            me = User.current_user()
            me.calconsumed = 0
            print(me.feed)

            for i in me.feed:
                j = json.loads(i)
                #print(j)
                me.calconsumed = str(int(j['calories']) + int(me.calconsumed))
            me.save()
            return me.calconsumed
Ejemplo n.º 48
0
def fakeNewCheerFromCSV(csvLines, updateFrequency, length, objID, username,
                        pwd):
    '''
    use like this...
    fakeNewLocations(runnerLocations, 1, 40)
    runnerLocations is the query,
    1 is going to send the next location every 1 second,
     and will do this for 40 seconds
    '''
    u = User.login(username, pwd)
    updateNum = 0
    for line in csvLines[1:]:
        lat, lon, time, username, user_objid, dist, runT = line.strip().split(
            ",")
        sl = SpectatorLocations(location=GeoPoint(latitude=float(lat),
                                                  longitude=float(lon)),
                                time=datetime.datetime.now(),
                                user=u,
                                distance=float(dist),
                                duration=runT)
        sl.save()

        base_url = 'https://crowdcheerdb.herokuapp.com/parse/classes/CurrSpectatorLocation/' + objID
        header = {
            'X-Parse-Application-Id':
            'QXRTROGsVaRn4a3kw4gaFnHGNOsZxXoZ8ULxwZmf'
        }
        data = {
            "duration": runT,
            "distance": float(dist),
            "location": {
                "__type": "GeoPoint",
                "latitude": float(lat),
                "longitude": float(lon)
            }
        }
        resp = requests.put(base_url, headers=header, data=json.dumps(data))
        print resp
        print "updated %s times" % updateNum
        print "distance : %s , duration : %s" % (sl.distance, sl.duration)
        updateNum += 1
        if (updateNum > length):
            break
        sleep(updateFrequency)
Ejemplo n.º 49
0
    def POST(self, request):
        story = models.story.Story.active_story()
        if not story:
            return ("Cannot find active story", 400)

        post = models.post.Post(text=request.values.get("text"),
                                author=User.current_user(),
                                voted_users=[],
                                archived=False)

        if not post or not post.valid():
            return ("Post invalid " + str(post), 400)

        post.save()

        story.snippets.append(post)
        story.save()

        return flask.redirect('/')
Ejemplo n.º 50
0
	def signUp(self):
		"""Sends a HTTP request to verify email address and attemps to create a new user in the database if all of the credentials are valid"""
		self.response = json.loads(urllib.request.urlopen("https://api.kickbox.io/v2/verify?email="+self.signUpCredentials['email']+"&apikey="+self.emailKey).read().decode("utf-8"))
		if self.response['result'] != 'deliverable' and self.response['reason'] != 'accepted_email':
			self.emailVerfication = 'Invalid'
			print("\nInvalid Email.\n")
			time.sleep(1)
		else:
			self.emailVerfication = 'Valid'
		try:
			if self.emailVerfication == 'Valid':
				self.user = User.signup(self.signUpCredentials['userID'], self.signUpCredentials['password'], email=self.signUpCredentials['email'], full_name=self.signUpCredentials['full_name'])	  # creates a new user in the database (user, password, other records)
				self.signUpSuccessful = True
				self.full_name = self.signUpCredentials['full_name']
				print("\nSigned up successfully!\n")
		except:
		 	self.signUpSuccessful = False
		 	print("\nInvalid Email.\n")
		 	time.sleep(1)
		return self.signUpSuccessful
Ejemplo n.º 51
0
import os

os.environ["PARSE_API_ROOT"] = "http://3.16.42.236:80/parse"


from parse_rest.datatypes import File
from parse_rest.connection import register
from parse_rest.user import User

APPLICATION_ID = 'APPID'
REST_API_KEY = 'RESTAPIK'
MASTER_KEY = 'MASTERK'

register(APPLICATION_ID, REST_API_KEY, master_key=MASTER_KEY)

u = User.login("test_user", "1234567890")


from parse_rest.datatypes import File

#plateToMatch='"plate": ' 
u.carLicensePlate=''



with  open('placas2.txt', 'r+') as placas_txt:
	for line in placas_txt:
		#if plateToMatch in line:
		u.carLicensePlate = line
		print(u.carLicensePlate)
		u.save()
Ejemplo n.º 52
0
 def testCanLogin(self):
     self._get_user()  # User should be created here.
     user = User.login(self.username, self.password)
     self.assertTrue(user.is_authenticated(), 'Login failed')
Ejemplo n.º 53
0
def logout():
    try:
        User.logout_user()
    except:
        return "Error"
Ejemplo n.º 54
0
 def testCanSignUp(self):
     self._destroy_user()
     user = User.signup(self.username, self.password)
     self.assertIsNotNone(user)
     self.assertEqual(user.username, self.username)
Ejemplo n.º 55
0
def login(username, password):
    try:
        u = User.login(username, password)
    except:
        return "Error: User login failed"
    return u
Ejemplo n.º 56
0
 def _get_logged_user(self):
     if User.Query.filter(username=self.username).exists():
         return User.login(self.username, self.password)
     else:
         return self._get_user()
Ejemplo n.º 57
0
import time
from io import BytesIO

from tkinter import *

import requests
from PIL import ImageTk, Image

from parse_rest.connection import register
from parse_rest.user import User

import parsepy
import voice_command

register(APP_ID, API_KEY, master_key=None)
user = User.login(USER, PASSWORD)
current_item = parsepy.item()
last_name = " "


def start(barcode, wake, speaker, detected_object):
    # Root: Define the tkinter root.
    root = Tk()
    root.title('IRMA Refrigerator Management System')
    root.geometry("900x800")
    # root.attributes("-fullscreen", True)
    # root.columnconfigure(0, weight=1)
    # root.rowconfigure(0, weight=1)

    # Frame: Define a frame that covers the entire root window.
    root_frame = Frame(root, padx=3, pady=3)
Ejemplo n.º 58
0
 def user_voted(self, session):
     with SessionToken(session):
         return bool([
             user for user in self.voted_users
             if user['objectId'] == User.current_user().objectId
         ])
Ejemplo n.º 59
0
 def _get_user(self):
     try:
         user = User.signup(self.username, self.password)
     except:
         user = User.Query.get(username=self.username)
     return user
Ejemplo n.º 60
0
from parse_rest.user import User
from parse_rest.connection import SessionToken
import sys

is_prod = len(sys.argv) > 1 and sys.argv[1] == 'prod'

if is_prod:
	facilityId = '44SpXTtzUl'
	register('5pYOx25qvyg4IVXyu128IuRlbnJtwLgwCTsHXCpO', 'xkuupM8jCHRcR15G0WJ1BjAixZEzf8vrTiyWrUjr',
			master_key='2xUvmLlh5L0oh7SE7XrlFxtaLkA8kUxP0vI8sFjl')
else:
	facilityId = 'ZsFlRbIPqy'
	register('jjQlIo5A3HWAMRMCkH8SnOfimVfCi6QlOV9ZNO2T', 'Fe2miwj6i5iAKC9Pyzl6KdRRk9QmV9lt7BmbqP4E', 
			master_key='bswubKWU9MvLuQdh8tYbAt9qXu5guxaZBIMTmHsc')

u = User.login("*****@*****.**", "test")

shifts = {
	'Charge Nurse': [
		[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
		[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
		[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
	],
	'NA': [
		[0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3],
		[0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3],
		[0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3],
		[0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3]
	],
	'Nurse': [