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()) ))
Example #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)
Example #3
0
def delete_sample_users():
  for username, password, email in sample_users:
    try:
      u = User.login(username, password)
      u.delete()
    except:
      pass
Example #4
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')
Example #5
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)
Example #6
0
def test():
    u = User.login("arjun", "password")

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

    return render_template('test.html', u="blah")
Example #7
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"})
Example #8
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
Example #9
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))
Example #10
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
Example #11
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()
Example #12
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()
Example #13
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)
Example #14
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]
Example #15
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")
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')
Example #17
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
def fakeNewRunFromCSV(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, 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()

        connection = httplib.HTTPSConnection('api.parse.com', 443)
        objectPath = '/1/classes/CurrRunnerLocation/' + objID
        connection.connect()
        connection.request('PUT', objectPath, json.dumps({
            
            "time": {
                "__type": "Date",
                "iso": datetime.datetime.utcnow().isoformat()
            },
            "speed": float(speed),
            "duration": runT,
            "distance": float(dist),
            "location": {
                "__type": "GeoPoint",
                "latitude": float(lat), 
                "longitude": float(lon)
            }
        }), {
            "X-Parse-Application-Id": "QXRTROGsVaRn4a3kw4gaFnHGNOsZxXoZ8ULxwZmf",
            "X-Parse-REST-API-Key": "BCJuFgG7GVxZfnc2mVbt2dzLz4bP7qAu16xaItXB",
            "Content-Type": "application/json"
        })
        result = json.loads(connection.getresponse().read())
        print result

        print "updated %s times" % updateNum
        print "distance : %s , duration : %s" % (rl.distance, rl.duration)
        updateNum += 1
        if (updateNum > length):
            break
        sleep(updateFrequency)
Example #19
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
Example #20
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        session['username'] = username
        session['password'] = password
        u = User.login(username, password)
        u.save()
        return redirect(url_for('index'))
    else:
        if 'username' in session:
            return redirect(url_for('index'))
        else:
            return render_template('login.html', new=True)
Example #21
0
def index():
    if 'username' in session:
        username = escape(session['username'])
        password = escape(session['password'])
        user = User.login(username, password)
        if request.method == 'POST':
            post = Post(text=request.form['post'])
            file = request.files['file']
            if file:
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                headers = {
                "X-Parse-Application-Id": "h2Co5EGV2YoBuPL2Cl7axkcLE0s9FNKpaPcpSbNm",
                "X-Parse-REST-API-Key": "o59euguskg7BBNZlFEuVxTNL0u93glStq7memfVH",
                "Content-Type": "image/jpeg"
                }
                connection = httplib.HTTPSConnection('api.parse.com', 443)
                connection.connect()
                connection.request('POST', '/1/files/' + filename, open(filename, 'rb'), headers)
                result = json.loads(connection.getresponse().read())
                post.imgUrl = result['url'];

            post.circles = user.postingTo
            post.user = user
            post.save()
            return redirect(url_for('index'))
        else:
            posts = []
            allFriends = Circle.Query.get(owner=user, name="all")
            for friend in allFriends.users:
                friendObj = User.Query.get(objectId=friend.get('objectId'))
                circlesIAmIn = []
                for circle in friendObj.circles:
                    circleObj = Circle.Query.get(objectId=circle.get('objectId'))
                    for u in circleObj.users:
                        if u.get('objectId') == user.objectId:
                            circlesIAmIn.append(circleObj.name)
                friendPosts = Post.Query.filter(user=friendObj)
                for post in friendPosts:
                    for i in circlesIAmIn:
                        if i in post.circles:
                            posts.append(post)
                            break

            sortedPosts = sorted(posts, key=lambda x: x.createdAt, reverse=True)
            return render_template('home.html', user=user, posts=sortedPosts)
    else:
        session.pop('username', None)
        session.pop('password', None)
        return render_template('signup.html')
Example #22
0
def updateCircles():
    if 'username' in session:
        username = escape(session['username'])
        password = escape(session['password'])
        user = User.login(username, password)
        if request.method == 'POST':
            cKeys = dict((key, request.form.getlist(key)) for key in request.form.keys())
            user.postingTo = list(cKeys.keys())
            user.save()
            return redirect(url_for('settings'))

    else:
        session.pop('username', None)
        session.pop('password', None)
        return render_template('signup.html')
Example #23
0
def parse_login(email):	
	
	email = email.lower()

	try:
		user = get_parse_user_by_email(email)
	except:
		return {'error': "No one has signed up with this address."}
		
	if not user.emailVerified:
		return {'error': "Email address not verified. Please check inbox."}

	u = User.login(email, "pass")
	header = u.session_header()
	return {'token': header['X-Parse-Session-Token'], 'ref': u.ref}
Example #24
0
def billPay(billid=None):
    u = User.login("arjun", "password")

    if not billid:
        return

    bill = Bills.Query.all(objectId=u.username)
    c = bill.cost

    acc_balance = u.acctBalance
    if acc_balance > c:
        acc_balance = acc_balance - c
        u.acctBalance = acc_balance
        u.save()
        bill.paid = True
        bill.save()
Example #25
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'))
Example #26
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
Example #27
0
def settings():
    if 'username' in session:
        old_user = escape(session['username'])
        old_pass = escape(session['password'])
        userLogin = User.login(old_user, old_pass)
        if request.method == 'POST' and userLogin:
            if request.form['username'] != '':
                userLogin.username = request.form['username']
            if request.form['password'] != '':
                userLogin.password = request.form['password']

            file = request.files['file']
            if file:
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                headers = {
                "X-Parse-Application-Id": "h2Co5EGV2YoBuPL2Cl7axkcLE0s9FNKpaPcpSbNm",
                "X-Parse-REST-API-Key": "o59euguskg7BBNZlFEuVxTNL0u93glStq7memfVH",
                "Content-Type": "image/jpeg"
                }
                connection = httplib.HTTPSConnection('api.parse.com', 443)
                connection.connect()
                connection.request('POST', '/1/files/' + filename, open(filename, 'rb'), headers)
                result = json.loads(connection.getresponse().read())
                userLogin.profilePic = result['url'];

            userLogin.save()
            if request.form['username'] != '' or request.form['password'] != '':
                session.pop('username', None)
                session.pop('password', None)
                return render_template('login.html')

        circles = []
        for circle in userLogin.circles:
            c = Circle.Query.get(objectId=circle.get('objectId'))
            circles.append(c.name)

        checked = list(set(circles) & set(userLogin.postingTo))
        unchecked = list(set(circles) - set(checked))
        return render_template('settings.html', user=userLogin, checked=checked, unchecked=unchecked, bad=not userLogin.emailVerified)
    else:
        session.pop('username', None)
        session.pop('password', None)
        return render_template('signup.html')
Example #28
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)
Example #29
0
def addAccount():
    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 'routingNo' in req or not 'acctNo' in req:
        return json.dumps({"status": "fail",
                "reason": "Must include routing and account number."})


    # 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."})

    # validate the account with a $1 charge
    res = achCharge(1, req['routingNo'], req['acctNo'])

    if res['CmdStatus'] != 'Approved':
        return json.dumps({"status": "fail",
                "reason": "Account invalid."})

    """
    {u'Authorize': u'5.00', u'Purchase': u'5.00', u'AcctNo': u'XXXXXXXXXXXXXX67', u'ResponseOrigin': u'Processor', u'CmdStatus': u'Approved', u'AuthCode': u'272-172', u'TranCode': u'Authorize', u'UserTraceData': u'', u'TextResponse': u'Approved', u'InvoiceNo': u'111020141280', u'CardType': u'ACH', u'DSIXReturnCode': u'000000', u'MerchantID': u'6013521114', u'OperatorID': u'TEST'}
    """

    # save the db updates now that we know they're valid
    u.routingNo = req['routingNo']
    u.acctNo = req['acctNo']
    u.save()

    return json.dumps({"status":"success"})
Example #30
0
def login():
    global user, notifications, messages, following, follower
   # print 'cookie in homepage: '
    print request.cookies
    users = User.Query.all();

    if request.method == 'POST':
        data = request.form

        try:
            user = User.login(data['username'], data['password'])
        except:
            user = None
            flash('Incorrect username or password', 'info')
        # login_user(user)

        if user:
            username = data.getlist('username')[0]

            notifications = Notification.Query.filter(to=username)
            messages_query = Message.Query.filter(toUser=username)
            messages = []
            for m in messages_query:
                messages.append(m)
            resp = make_response(render_template('organizations/organizations.html', notifications=notifications, messages=messages))
            following_query = Following.Query.filter(subscriber=user)
            following = []
            for u in following_query:
                following.append(u.user)
            follower_query = Following.Query.filter(user=user)
            follower = []
            for u in follower_query:
                follower.append(u.subscriber)
            resp.set_cookie('username', username)

            resp.set_cookie('user_objectId', user.objectId)

            return resp

    return make_response(render_template('login.html'))
Example #31
0
def send_welcome_email(email):

	user = User.Query.all().filter(email=email, welcomed=False)
	user = [u for u in user]

	try:
		if len(user) > 0:
			user = user[0]
		
			subject = "Our Gift to You | CabTools"
			title = "We love you"
			link = "<a href='http://www.cabtools.com/?ref=%s'>http://www.cabtools.com/?ref=%s</a>" % (str(user.ref), str(user.ref))
			body = "That's why we're giving you full access to CabTools for a month. Get CabTools <b>free for 6 months</b> if you get 5 people to sign-up. Share the link below."	
			body += "</br></br>%s" % (link)

			send_template_email(user.email, subject, title, body)	
			
			u = User.login(email, "pass")
			u.welcomed = True
			u.save()
	except:
		pass
 def change_demo_user(self, cid='NAACL2015'):
     demo_user = User.login("demo", "demo")
     
     regex = re.compile("([a-z])(\d+)")
     
     gs = regex.findall(demo_user.token)
     
     new_tokens = []
     if gs:
         for g in gs:
             if g[0] == 'n':
                 id = int(g[1]) + 1
                 new_id = "%04d" % (id,)
                 print "new user token:", new_id
                 new_tokens.append('"' +g[0] + new_id + '"')
             else:
                 new_tokens.append('"' +g[0] + g[1] + '"')
     
     demo_user.token = '['+','.join(new_tokens)+']' 
     demo_user.save()
     
     self.remove_sumamry(cid)
Example #33
0
def friendCircles():
    if 'username' in session:
        username = escape(session['username'])
        password = escape(session['password'])
        user = User.login(username, password)
        fid = request.form['fid']
        print fid

        updated = []
        for key in request.form.keys():
            if key != 'fid':
                updated.append(key)

        for circleRef in user.circles:
            circle = Circle.Query.get(objectId=circleRef['objectId'])
            if circle.name == 'all':
                continue

            userIds = []
            for u in circle.users:
                userIds.append(u['objectId'])
            if circle.name in updated:
                # add to this circle if necessary
                if fid not in userIds:
                    friend = User.Query.get(objectId=fid)
                    circle.users.append(friend)
            else:
                # remove from this circle if necessary
                if fid in userIds:
                    circle.users[:] = [x for x in circle.users if x.get('objectId') != fid]

            circle.save()
            return redirect(url_for('circles'))
    else:
        session.pop('username', None)
        session.pop('password', None)
        return render_template('signup.html')
Example #34
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
Example #35
0
  def test_create_ping(self):
    assignTask = Function("assignTask")
    ping = Function("ping")
    u = User.login('redsox55', 'secure123')
    assignee = User.Query.get(username='******')
    with SessionToken(u.sessionToken):
      title = 'serha34g444'
      response = assignTask(
        title=title,
        description="Send a ping to this task",
        watchers=[user[2] for user in sample_users],
        score=2,
        assignee=assignee.email,
      )
    self.assertIn('task', response['result'])

    with SessionToken(u.sessionToken):
      task = Task.Query.get(title=title)
      response = ping(taskId=task.objectId)

    task = Task.Query.get(title=title)
    self.assertIn('task', response['result'])
    self.assertIn('ping', response['result'])
    self.assertEqual(task.score, 1)
Example #36
0
def edit():
    if 'username' in session:
        circlesIn = []
        circlesAll = []
        username = escape(session['username'])
        password = escape(session['password'])
        user = User.login(username, password)
        f = request.args.get('friend')
        friend = User.Query.get(objectId=f)

        circles = Circle.Query.filter(owner=user)
        for circle in circles:
            if circle.name != 'all':
                circlesAll.append(circle.name)
            for u in circle.users:
                if u['objectId'] == friend.objectId:
                    if circle.name != 'all':
                        circlesIn.append(circle.name)

        checked = circlesIn
        unchecked = list(set(circlesAll) - set(circlesIn))
        return render_template('edit.html', checked=checked, unchecked=unchecked, fid=f)
    else:
        return render_template('signup.html')
Example #37
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')
Example #38
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()
Example #39
0
def login(username, password):
    try:
        u = User.login(username, password)
    except:
        return "Error: User login failed"
    return u
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': [
Example #41
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)
Example #42
0
from parse_rest.connection import register as parse_register
from parse_rest.user import User
import random
import datetime
import sys

from objects import Bills

PARSE_APP_ID = ''
PARSE_API_KEY = ''
PARSE_MASTER_KEY = ''

parse_register(PARSE_APP_ID,
               PARSE_API_KEY,
               master_key=PARSE_MASTER_KEY)

u = User.login("arjun", "password")

for i in range(int(sys.argv[1])):
    cost = random.randrange(100, 50000)/100.0
    user = random.choice(['dakota', 'arjun'])
    type = random.choice(['gas', 'electric', 'water'])

    dueDay = random.randint(1,20)
    dueMonth = random.randint(1,12)
    dueDate = datetime.datetime(2015, dueMonth, dueDay)

    b = Bills(due=dueDate, type=type, cost=cost, username=user)
    b.save()
Example #43
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()