Example #1
0
 def get(self):
     id = get_user_id()
     #just loops and prints every question from query
     review = models.get_oldest_questions(True, False,
                                          models.getUser(id).username)
     submitted = models.get_oldest_questions(False, False,
                                             models.getUser(id).username)
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html', page_params)
             return
     page_params = {
         'user_email': get_user_email(),
         'login_url': users.create_login_url(),
         'logout_url': users.create_logout_url('/'),
         'user_id': id,
         'review': review,
         'submitted': submitted,
         'admin': is_admin
     }
     render_template(self, 'viewDatabase.html', page_params)
Example #2
0
def signUp():
	if 'logged_in' in session:
		return redirect(url_for("friends"))
	if request.method == "POST":
		email=str(request.form['email'])
		fname=str(request.form['fname'])
		lname=str(request.form['lname'])
		phone=str(request.form['phone'])
		name=fname + " " + lname
		password=str(request.form['pass'])
		conpassword=str(request.form['conpass'])
		Pass=hashlib.sha256(password)
		hashPass=Pass.hexdigest()
		user1 = dbHandler.getUser(email)
		user2 = dbHandler.getUser(phone)
		if password == conpassword: 
			if user1 :
				flash("Email-ID Already Exists.",'danger')
				redirect(url_for("signUp"))
			elif user2 :
				flash("Phone Number Already Exists.",'danger')
				return render_template("signup.html")
			else:
				dbHandler.insertUser(email,name,hashPass,phone)	
				return redirect(url_for("login"))
		else:
			flash("Password don't match",'danger')
			return render_template("signup.html")
	return render_template("signup.html")
Example #3
0
    def get(self):
        id = get_user_id()
        is_admin = 0
        if users.is_current_user_admin():
            is_admin = 1
        if id is not None:
            q = models.check_if_user_exists(id)
            if q == None:
                page_params = {
                    'upload_url': blobstore.create_upload_url('/profile'),
                    'user_email': get_user_email(),
                    'login_url': users.create_login_url(),
                    'logout_url': users.create_logout_url('/'),
                    'user_id': get_user_id(),
                    'profile': models.getUser(id),
                    'admin': is_admin
                }
                render_template(self, 'createProfile.html', page_params)
                return
        category = self.request.get('category') + ':' + self.request.get(
            'subcategory')
        number = self.request.get('number')
        mine = self.request.get('mine')
        timed = self.request.get('timed')
        if mine == 'mine':
            questions = models.getQuestionsCatUsr(category, int(number),
                                                  models.getUser(id).username)
        else:
            questions = models.getQuestionsCat(category, int(number))

        if questions is None:
            num = 0
            jList = []
        else:
            num = len(questions)
            qList = []
            for q in questions:
                #exclude removes the properties we do no need to have passed to the html from the question object
                temp = q.to_dict(exclude=[
                    'category', 'creator', 'accepted', 'up_voters',
                    'down_voters', 'create_date'
                ])
                qList.append(temp)
            jList = json.dumps(qList, default=obj_dict)

        page_params = {
            'user_id': get_user_id(),
            'num': num,
            'question_list': jList,
            'timed': timed,
            'user_email': get_user_email(),
            'login_url': users.create_login_url(),
            'logout_url': users.create_logout_url('/'),
            'admin': is_admin,
        }
        render_template(self, 'quiz.html', page_params)
Example #4
0
    def post(self):
        #will need to be moved to occur after form submission
        id = get_user_id()
        user = models.getUser(id)
        if user is None:
            models.createUser(id)
            user = models.getUser(id)
        try:
            upload_files = self.get_uploads()
            blob_info = upload_files[0]
            type = blob_info.content_type
            models.createUser(id)
            name = self.request.get("name")
            year = self.request.get("year")
            interests = self.request.get("interests")
            employer = self.request.get("employer")
            bio = self.request.get("bio")
            username = self.request.get('username')
            id = get_user_id()
            if username == "":
                username = user.username
            # if the uploaded file is an image
            if type in ['image/jpeg', 'image/png', 'image/gif', 'image/webp']:
                image = blob_info.key()
                models.updateUser(id, name, year, interests, bio, employer,
                                  username, image)

            # if the uploaded file is not an image
            else:
                models.updateUser(id, name, year, interests, bio, employer,
                                  username, user.image_url)

            self.redirect('/profile?id=' + id)
        # no image to upload
        except IndexError:
            id = get_user_id()
            models.createUser(id)
            name = self.request.get("name")
            year = self.request.get("year")
            interests = self.request.get("interests")
            employer = self.request.get("employer")
            bio = self.request.get("bio")
            username = self.request.get('username')
            if username == "":
                username = user.username
            id = get_user_id()
            models.updateUser(id, name, year, interests, bio, employer,
                              username, user.image_url)
            self.redirect('/profile?id=' + id)
Example #5
0
    def post(self):
        #will need to be moved to occur after form submission
        id = get_user_id()
        user = models.getUser(id)
        if user is None:
            models.createUser(id)
            user = models.getUser(id)
        try:
            upload_files = self.get_uploads()
            blob_info = upload_files[0]
            type = blob_info.content_type
            models.createUser(id)
            name = self.request.get("name")
            year = self.request.get("year")
            interests = self.request.get("interests")
            employer = self.request.get("employer")
            bio = self.request.get("bio")
            username= self.request.get('username')
            id = get_user_id()
            if username == "":
                username = user.username
            # if the uploaded file is an image
            if type in ['image/jpeg', 'image/png', 'image/gif', 'image/webp']:
                image = blob_info.key()
                models.updateUser(id, name, year, interests, bio, employer,username, image)

            # if the uploaded file is not an image
            else:
                models.updateUser(id, name, year, interests, bio,
                        employer,username, user.image_url)

            self.redirect('/profile?id=' + id)
        # no image to upload
        except IndexError:
            id = get_user_id()
            models.createUser(id)
            name = self.request.get("name")
            year = self.request.get("year")
            interests = self.request.get("interests")
            employer = self.request.get("employer")
            bio = self.request.get("bio")
            username = self.request.get('username')
            if username == "":
                username = user.username
            id = get_user_id()
            models.updateUser(id, name, year, interests, bio,
                    employer,username, user.image_url)
            self.redirect('/profile?id=' + id)
Example #6
0
 def get(self):
     id = get_user_id()
     user = models.getUser(id)
     if user is None:
         self.redirect('/profile?id=' + id)
     else:
         self.redirect('/')
Example #7
0
 def get(self):
     id = get_user_id()
     trueList = models.getCategoryList(True)
     falseList = models.getCategoryList(False)
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html' ,page_params)
             return
     page_params = {
         'user_id': get_user_id(),
         'trueCatList': trueList,
         'falseCatList': falseList,
         'user_email': get_user_email(),
         'login_url': users.create_login_url(),
         'logout_url': users.create_logout_url('/'),
         'admin': is_admin,
         }
     render_template(self, 'reviewCategories.html', page_params)
Example #8
0
 def get(self):
     id = get_user_id()
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html' ,page_params)
             return
     newList = models.getCategoryList()
     page_params = {
         'catList': newList,
         'upload_urlQ': blobstore.create_upload_url('/NewQuestion'),
         'user_email': get_user_email(),
         'login_url': users.create_login_url(),
         'logout_url': users.create_logout_url('/'),
         'user_id': id,
         'admin' : is_admin
     }
     render_template(self, 'newQuestionSubmit.html', page_params)
Example #9
0
 def get(self):
     user = auth.getCurrentUser()
     name = "Web"
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except models.DeviceDoesNotExistError:
             device = models.DeviceData(user=user_data, name=name).save()
         over_quota = False
         try:
             channel = channels.Channel(device.address, override_quota=user_data.immune())
             channel_token = channel.token
         except channels.OverQuotaError:
             over_quota = True
             channel_token = "overquota"
         template_values = {
             "channel_id": channel_token,
             "device": device.address,
             "device_name": device.name,
             "devices": user_data.getDevices(),
             "over_quota": over_quota,
         }
         path = os.path.join(os.path.dirname(__file__), "devlinks_index.html")
         self.response.out.write(template.render(path, template_values))
     else:
         self.redirect(users.create_login_url(self.request.uri))
Example #10
0
    def get(self):
        id = get_user_id()
        #just loops and prints every question from query
        review = models.get_oldest_questions(True, False, None)
        is_admin = 0
        if users.is_current_user_admin():
            is_admin = 1
        #else:
        # If not admin, redirect to your questions
        # NOTE: non-admins can now view this page
        #return self.redirect("/ReviewMyQuestions")

        if id is not None:
            q = models.check_if_user_exists(id)
            if q == None:
                page_params = {
                    'upload_url': blobstore.create_upload_url('/profile'),
                    'user_email': get_user_email(),
                    'login_url': users.create_login_url(),
                    'logout_url': users.create_logout_url('/'),
                    'user_id': get_user_id(),
                    'profile': models.getUser(id),
                    'admin': is_admin
                }
                render_template(self, 'createProfile.html', page_params)
                return
        page_params = {
            'user_email': get_user_email(),
            'login_url': users.create_login_url(),
            'logout_url': users.create_logout_url('/'),
            'user_id': id,
            'review': review,
            'admin': is_admin
        }
        render_template(self, 'viewDatabase.html', page_params)
Example #11
0
def login():
	if 'logged_in' in session:
		return redirect(url_for("friends"))
	if request.method == "POST":
		data=str(request.form["data"])
		password=str(request.form["pass"])
		Pass=hashlib.sha256(password)
		hashPass=Pass.hexdigest()
		user = dbHandler.getUser(data)
		userPass = dbHandler.getUserPass(data)
		if user :
			if userPass[0] == hashPass:
				session['logged_in']=True
				session['email']=user[1]
				session['name']=user[0]
				return redirect(url_for("friends"))
			else:
				flash("Invalid Password",'danger')
		 		return render_template("login.html")
		else:
			flash("No such user",'danger')
			return render_template("login.html")
		cursor.close()
	else:
		return render_template("login.html")
Example #12
0
 def get(self, name=False):
     self.response.headers.add_header("Access-Control-Allow-Origin", "*")
     user = auth.getCurrentUser()
     response = {}
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         if not name:
             name = "Chrome"
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except models.DeviceDoesNotExistError:
             device = models.DeviceData(user=user_data, name=name).save()
         try:
             channel = channels.Channel(device.address,
                                        override_quota=user_data.immune())
             response['token'] = channel.token
             if channel.cached:
                 response['code'] = 304
             else:
                 response['code'] = 200
         except channels.OverQuotaError:
             response['code'] = 503
             response['token'] = 'overquota'
             response['message'] = "Server is over quota."
     else:
         response['code'] = 401
         response['message'] = 'Not logged in.'
     self.response.out.write(simplejson.dumps(response))
Example #13
0
 def get(self, name=False):
     self.response.headers.add_header("Access-Control-Allow-Origin", "*")
     user = auth.getCurrentUser()
     response = {}
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         if not name:
             name = "Chrome"
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except models.DeviceDoesNotExistError:
             device = models.DeviceData(user=user_data, name=name).save()
         try:
             channel = channels.Channel(device.address, override_quota=user_data.immune())
             response["token"] = channel.token
             if channel.cached:
                 response["code"] = 304
             else:
                 response["code"] = 200
         except channels.OverQuotaError:
             response["code"] = 503
             response["token"] = "overquota"
             response["message"] = "Server is over quota."
     else:
         response["code"] = 401
         response["message"] = "Not logged in."
     self.response.out.write(simplejson.dumps(response))
Example #14
0
 def get(self):
     id = get_user_id()
     jAson = models.getAllUserScores()
     userList = json.dumps(jAson)
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html', page_params)
             return
     newList = models.getCategoryList()
     page_params = {
         'category': 'ALL',
         'catList': newList,
         'user_id': get_user_id(),
         'list': jAson,
         'user_email': get_user_email(),
         'login_url': users.create_login_url(),
         'logout_url': users.create_logout_url('/'),
         'admin': is_admin,
     }
     render_template(self, 'leaderboard.html', page_params)
Example #15
0
 def get(self):
     id = get_user_id()
     user = models.getUser(id)
     if user is None:
         self.redirect('/profile?id=' + id)
     else:
         self.redirect('/')
Example #16
0
 def get(self):
     id = get_user_id()
     trueList = models.getCategoryList(True)
     falseList = models.getCategoryList(False)
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html', page_params)
             return
     page_params = {
         'user_id': get_user_id(),
         'trueCatList': trueList,
         'falseCatList': falseList,
         'user_email': get_user_email(),
         'login_url': users.create_login_url(),
         'logout_url': users.create_logout_url('/'),
         'admin': is_admin,
     }
     render_template(self, 'reviewCategories.html', page_params)
Example #17
0
 def get(self):
     id = get_user_id()
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html', page_params)
             return
     newList = models.getCategoryList()
     page_params = {
         'catList': newList,
         'upload_urlQ': blobstore.create_upload_url('/NewQuestion'),
         'user_email': get_user_email(),
         'login_url': users.create_login_url(),
         'logout_url': users.create_logout_url('/'),
         'user_id': id,
         'admin': is_admin
     }
     render_template(self, 'submitQuestion.html', page_params)
Example #18
0
 def get(self):
     id = get_user_id()
     jAson = models.getAllUserScores()
     userList = json.dumps(jAson)
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html' ,page_params)
             return
     newList = models.getCategoryList()
     page_params = {
         'category': 'ALL',
         'catList': newList,
         'user_id': get_user_id(),
         'list': jAson,
         'user_email': get_user_email(),
         'login_url': users.create_login_url(),
         'logout_url': users.create_logout_url('/'),
         'admin': is_admin,
         }
     render_template(self, 'leaderboard.html', page_params)
Example #19
0
 def get(self):
     id = get_user_id()
     #just loops and prints every question from query
     review = models.get_oldest_questions(True,False)
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html' ,page_params)
             return
     page_params = {
         'user_email': get_user_email(),
         'login_url': users.create_login_url(),
         'logout_url': users.create_logout_url('/'),
         'user_id': id,
         'review': review,
         'admin' : is_admin
     }
     render_template(self, 'viewDatabase.html', page_params)
Example #20
0
 def get(self):
     user = auth.getCurrentUser()
     name = "Web"
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except models.DeviceDoesNotExistError:
             device = models.DeviceData(user=user_data, name=name).save()
         over_quota = False
         try:
             channel = channels.Channel(device.address,
                                        override_quota=user_data.immune())
             channel_token = channel.token
         except channels.OverQuotaError:
             over_quota = True
             channel_token = 'overquota'
         template_values = {
             'channel_id': channel_token,
             'device': device.address,
             'device_name': device.name,
             'devices': user_data.getDevices(),
             'over_quota': over_quota
         }
         path = os.path.join(os.path.dirname(__file__),
                             'devlinks_index.html')
         self.response.out.write(template.render(path, template_values))
     else:
         self.redirect(users.create_login_url(self.request.uri))
Example #21
0
 def get(self):
     questionID = self.request.get('id')
     id = get_user_id()
     review = models.getQuestionFromURL(questionID)
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html' ,page_params)
             return
     page_params = {
         'upload_urlQE': blobstore.create_upload_url('/ReviewQuestion?id=' + questionID),
         'user_email': get_user_email(),
         'login_url': users.create_login_url(),
         'logout_url': users.create_logout_url('/'),
         'user_id': id,
         'review': review,
         'admin' : is_admin
     }
     render_template(self, 'questionReview.html', page_params)
Example #22
0
def addfriends():
	if request.method == "POST":
		if request.form['btn'] == 'Search':
			data=str(request.form['search'])
			user = dbHandler.getUser(data)
			if user:
				if user[1] == session['email']:
					flash("You cannot send a request to yourself",'danger')
					return render_template("addfriends.html")
				session['addFriend'] = user[1]
				session['addFriendName'] = user[0]
				return render_template('addfriends.html',user=user)
			else:
				flash("No such user",'danger')
				return redirect(url_for("addfriends"))
		else :
			user = request.form['btn']
			status = dbHandler.sendRequest(session['email'],session['addFriend'])
			if status == "sent":
				flash("Friend Request Sent",'success')
			else:
				flash(status+session['addFriendName'],'danger')
			del session['addFriend']
			del session['addFriendName']
			return render_template('addfriends.html')		
	return render_template('addfriends.html')
Example #23
0
 def get(self):
   id = self.request.get("id")
   profile = models.getUser(id)
   try:
    image = images.Image(blob_key=profile.image_url)
    self.send_blob(profile.image_url)
   except Exception:
    pass
Example #24
0
 def get(self):
     id = self.request.get("id")
     profile = models.getUser(id)
     try:
         image = images.Image(blob_key=profile.image_url)
         self.send_blob(profile.image_url)
     except Exception:
         pass
Example #25
0
    def get(self):
        if not get_user_email(
        ):  #stops from creating a profile if not logged in
            self.redirect("/")
            return
        id = self.request.get("id")
        is_admin = 0
        if users.is_current_user_admin():
            is_admin = 1
        if id is not None:
            q = models.check_if_user_exists(id)
            if q == None:
                page_params = {
                    'upload_url': blobstore.create_upload_url('/profile'),
                    'user_email': get_user_email(),
                    'login_url': users.create_login_url(),
                    'logout_url': users.create_logout_url('/'),
                    'user_id': get_user_id(),
                    'profile': models.getUser(id),
                    'admin': is_admin
                }
                render_template(self, 'createProfile.html', page_params)
                return
        user = models.getUser(id)

        categoryScores = models.getCatUserScore(get_user_id())
        page_params = {
            'upload_url': blobstore.create_upload_url('/profile'),
            'user_email': get_user_email(),
            'login_url': users.create_login_url(),
            'logout_url': users.create_logout_url('/'),
            'user_id': get_user_id(),
            'profile': user,
            'numScores': len(categoryScores),
            'categoryScores': categoryScores,
            'admin': is_admin,
        }
        render_template(self, 'profile.html', page_params)
Example #26
0
    def get(self):
        if not get_user_email(): #stops from creating a profile if not logged in
            self.redirect("/")
            return
        id = self.request.get("id")
        is_admin = 0
        if users.is_current_user_admin():
            is_admin = 1
        if id is not None:
            q = models.check_if_user_exists(id)
            if q == None:
                page_params = {
                    'upload_url': blobstore.create_upload_url('/profile'),
                    'user_email': get_user_email(),
                    'login_url': users.create_login_url(),
                    'logout_url': users.create_logout_url('/'),
                    'user_id': get_user_id(),
                    'profile': models.getUser(id),
                    'admin': is_admin
                }
                render_template(self, 'createProfile.html' ,page_params)
                return
        user = models.getUser(id)

        categoryScores = models.getCatUserScore(get_user_id())
        page_params = {
            'upload_url': blobstore.create_upload_url('/profile'),
            'user_email': get_user_email(),
            'login_url': users.create_login_url(),
            'logout_url': users.create_logout_url('/'),
            'user_id': get_user_id(),
            'profile': user,
            'numScores': len(categoryScores),
            'categoryScores':categoryScores,
            'admin': is_admin,
        }
        render_template(self, 'profile.html', page_params)
Example #27
0
 def get(self):
     user = users.get_current_user()
     uid = user.user_id()
     profile = models.getUser(uid)
     if not profile:
         nick = user.nickname()
         mail = ''
         if '@' in nick:
             mail = nick
             nick = utils.getNick(nick)
         isadmin = users.is_current_user_admin()
         ip = self.ipaddress
         profile = models.newEmptyUser(uid, nick, mail, isadmin, ip)
     data = {'profile': profile}
     self.show('myprofile', data)
def Checklogin(Formdata):
    Dict = getUser(Formdata['email'])
    if Dict == 0:
        return "No user Found. Please Register"
    elif Dict == 1:
        return "Account has been Suspended"
    # print(len(Dict[0]['password']))
    # print(len(Formdata['password']))
    if pwd_context.verify(Formdata['password'], Dict[0]['password']):
        session['fname'] = ""
        string = Dict[0]['fname']
        session['fname'] = string
        return True
    else:
        return "Wrong Password!"
Example #29
0
 def get(self):
   user = users.get_current_user()
   uid  = user.user_id()
   profile = models.getUser(uid)
   if not profile: 
     nick = user.nickname()
     mail = ''
     if '@' in nick:
       mail  = nick
       nick  = utils.getNick(nick)
     isadmin = users.is_current_user_admin()
     ip      = self.ipaddress
     profile = models.newEmptyUser(uid,nick,mail,isadmin,ip)
   data={'profile':profile}
   self.show('myprofile',data)
Example #30
0
 def post(self):
     user = auth.getCurrentUser()
     response = {}
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         payment_data = models.PaymentData(
             date=timestamp.now(),
             user=user_data,
             item=self.request.get("item_id"),
             order_number=self.request.get("order_number"),
             status="unconfirmed")
         payment_data.save()
Example #31
0
 def post(self):
     record = prospective_search.get_document(self.request)
     record_value = simplejson.loads(record.value)
     subscriber_keys = map(db.Key, self.request.get_all("id"))
     subscribers = db.get(subscriber_keys)
     datapoints = []
     stats_json = []
     for subscriber_key, subscriber in zip(subscriber_keys, subscribers):
         if not subscriber:
             prospective_search.unsubscribe(stats.StatsRecord, subscriber_key)
         else:
             datapoints.append(models.getStats(subscriber.datapoint, record.timestamp, duration="day"))
             datapoints.append(models.getStats(subscriber.datapoint, record.timestamp, duration="hour"))
     for datapoint in datapoints:
         if datapoint.datapoint == "active_users":
             try:
                 user = models.getUser(record_value["user"], False)
             except models.UserDoesNotExistError:
                 continue
             last_seen = user.last_seen
             new_last_seen = timestamp.now()
             if datapoint.duration == "day":
                 last_seen = last_seen.replace(hour=0, minute=0, second=0, microsecond=0)
                 new_last_seen = new_last_seen.replace(hour=0, minute=0, second=0, microsecond=0)
             if last_seen < new_last_seen:
                 user.updateLastSeen(new_last_seen)
                 user.save()
             else:
                 continue
         if datapoint.datapoint == "quota":
             datapoint.count = models.getQuota().amount
         else:
             datapoint.increment()
         json = {
             "datapoint": datapoint.datapoint,
             "value": datapoint.count,
             "date": datapoint.date.strftime("%D, %M %d %y"),
             "datestamp": int(time.mktime(datapoint.date.date().timetuple())) * 1000,
             "hour": datapoint.date.hour,
         }
         if datapoint.duration == "day":
             json["hour"] = "total"
         stats_json.append(json)
     db.put(datapoints)
     push = channels.Channel("[email protected]/Web", False)
     push.message = {"stats": stats_json}
     push.send()
     logging.debug(simplejson.dumps(stats_json))
Example #32
0
 def post(self):
     user = auth.getCurrentUser()
     response = {}
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         payment_data = models.PaymentData(
             date=timestamp.now(),
             user=user_data,
             item=self.request.get("item_id"),
             order_number=self.request.get("order_number"),
             status="unconfirmed",
         )
         payment_data.save()
Example #33
0
def login():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = dbHandler.getUser(username, password)
        if user == True:
            session['logged_in'] = True
            return redirect(url_for('welcome'))
        else:
            session['logged_in'] = False
            flash('Incorrect login details!')
            return render_template('login.html')
    else:
        session['logged_in'] = True
        return render_template('login.html')
Example #34
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = str(request.form['password'])
        user = getUser(username)
        if user:
            if sha256_crypt.verify(password, str(user.password)):
                session['logged_in'] = True
                session['username'] = username
                return redirect(url_for('index'))
            else:
                return render_template('login.html', msg="incorrect password")
        else:
            return render_template('login.html', msg="user not found")

    if request.method == 'GET':
        return render_template('login.html')
Example #35
0
 def get(self):
     user = users.User('*****@*****.**')
     try:
         user_data = models.getUser(user)
     except models.UserDoesNotExistError:
         user_data = models.UserData(user=user).save()
     try:
         device = models.getDevice("%s/%s" % (user.email(), "Web"))
     except models.DeviceDoesNotExistError:
         device = models.DeviceData(user=user_data, name="Web").save()
     channel = channels.Channel(device.address, override_quota=True)
     path = os.path.join(os.path.dirname(__file__), 'dashboard.html')
     stats_data = models.StatsData.all().order("-date").fetch(1000)
     template_values = {'channel_id': channel.token, 'stats': {}}
     stats = template_values['stats']
     for datapoint in stats_data:
         datestamp = int(
             time.mktime(datapoint.date.date().timetuple()) * 1000)
         hour = datapoint.date.hour
         if datestamp not in stats:
             stats[datestamp] = {
                 'datestamp': datestamp,
                 'date': datapoint.date,
                 'datapoints': {}
             }
         if datapoint.datapoint not in stats[datestamp]['datapoints']:
             stats[datestamp]['datapoints'][datapoint.datapoint] = {
                 'datapoint': datapoint.datapoint,
                 'values': {}
             }
         point_id = "%s" % hour
         if datapoint.duration == "day":
             point_id = "total"
         dp = datapoint.datapoint
         stats[datestamp]['datapoints'][dp]['values'][point_id] = {
             'datapoint': datapoint.datapoint,
             'datestamp': datestamp,
             'hour': hour,
             'count': int(datapoint.count),
             'duration': datapoint.duration
         }
     template_values['stats'] = stats
     logging.info(template_values)
     self.response.out.write(template.render(path, template_values))
Example #36
0
    def post(self):
        id = get_user_id()
        q = models.getUser(id)
        creator = q.username
        explanation = self.request.get('explanation')
        if not explanation:
            explanation = "No Explanation Provided"
        category = self.request.get('category')
        question = self.request.get('questiontext')
        answer1 = self.request.get('answer1')
        answer2 = self.request.get('answer2')
        answer3 = self.request.get('answer3')
        answer4 = self.request.get('answer4')
        answerid = self.request.get('answerid')
        try:
            upload_files = self.get_uploads()
            blob_info = upload_files[0]
            type = blob_info.content_type

            # if the uploaded file is an image
            if type in ['image/jpeg', 'image/png', 'image/gif', 'image/webp']:
                image = blob_info.key()
                questionID = models.createQuestion(category, question, answer1,
                                                   answer2, answer3, answer4,
                                                   answerid, explanation,
                                                   creator, False, image)

            # if the uploaded file is not an image
            else:
                questionID = models.createQuestion(category, question, answer1,
                                                   answer2, answer3, answer4,
                                                   answerid, explanation,
                                                   creator, False)

            self.redirect('/NewQuestion?id=' + questionID.urlsafe())

        # no image to upload
        except IndexError:
            questionID = models.createQuestion(category, question, answer1,
                                               answer2, answer3, answer4,
                                               answerid, explanation, creator,
                                               False)

        self.redirect('/NewQuestion?id=' + questionID.urlsafe())
Example #37
0
    def get(self):
        id = get_user_id()
        is_admin = 0
        if users.is_current_user_admin():
            is_admin = 1
        if id is not None:
            q = models.check_if_user_exists(id)
            if q == None:
                page_params = {
                    'upload_url': blobstore.create_upload_url('/profile'),
                    'user_email': get_user_email(),
                    'login_url': users.create_login_url(),
                    'logout_url': users.create_logout_url('/'),
                    'user_id': get_user_id(),
                    'profile': models.getUser(id),
                    'admin': is_admin
                }
                render_template(self, 'createProfile.html' ,page_params)
                return
        category = self.request.get('category')
        number = self.request.get('number')
        questions = models.getQuestionsCat(category,int(number))
        if questions is None:
            num = 0
            jList = []
        else:
            num = len(questions)
            qList = []
            for q in questions:
                #exclude removes the properties we do no need to have passed to the html from the question object
                temp = q.to_dict(exclude=['category','creator','accepted','up_voters','down_voters','create_date'])
                qList.append(temp)
            jList = json.dumps(qList, default=obj_dict)

        page_params = {
            'user_id': get_user_id(),
            'num': num,
            'question_list' : jList,
            'user_email': get_user_email(),
            'login_url': users.create_login_url(),
            'logout_url': users.create_logout_url('/'),
            'admin': is_admin,
            }
        render_template(self, 'answerQuestionsCat.html', page_params)
Example #38
0
 def post(self):
     self.response.headers.add_header("Access-Control-Allow-Origin", "*")
     user = auth.getCurrentUser()
     response = {}
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         name = self.request.get('name')
         if not name:
             name = "Chrome"
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except models.DeviceDoesNotExistError:
             device = models.DeviceData(name=name, user=user_data).save()
         receiver = None
         if self.request.get("receiver"):
             try:
                 receiver = models.getDevice(
                     "%s/%s" % (user.email(), self.request.get("receiver")))
             except models.DeviceDoesNotExistError:
                 receiver = models.DeviceData(
                     name=self.request.get("receiver"),
                     user=user_data).save()
         if receiver == None:
             receiver = device
         link = models.LinkData(url=self.request.get('link'),
                                sender=device,
                                receiver=receiver).save()
         if models.getQuota().amount >= models.getStats(
                 'channels').count or user_data.immune():
             channel = channels.Channel(receiver.address, False)
             channel.sendLink(link)
             response['code'] = 200
             response['link'] = link.url
         else:
             response['code'] = 503
             response['link'] = link.url
     else:
         response['code'] = 401
         response['link'] = self.request.get('link')
     self.response.out.write(simplejson.dumps(response))
Example #39
0
def myprofile(request):
    form = Form()
    fields = request.getForm()
    user = users.get_current_user()
    uid = user.user_id()

    # sanitize
    name = utils.toStr(fields.get('username', ''), 80)
    nick = utils.toStr(fields.get('nickname', ''), 40)
    email = utils.toStr(fields.get('email', ''), 80)
    token = utils.toStr(fields.get('token', ''), 80)
    userid = str(uid)
    if not name: name = 'Anonymous'

    # validate
    ok = True
    warn = []
    if userid != token:
        warn.append('You need to login to change your profile')
        ok = False
    # TODO: check for duplicate nick
    if not nick:
        warn.append('Nickname can not be empty')
        ok = False
    if ok:
        data = {
            'userid': uid,
            'nickname': nick,
            'username': name,
            'email': email
        }
        rec = models.saveUser(data)
        form.ok = True
        form.url = '%s/myprofile' % (app.root)
        form.redirect = True
    else:
        form.ok = False
        form.warn = warn
        form.data = {'profile': models.getUser(uid), 'warn': warn}
    return form


#---- END ----
Example #40
0
 def post(self, name="Chrome"):
     self.response.headers.add_header("Access-Control-Allow-Origin", "*")
     user = auth.getCurrentUser()
     device = None
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except:
             device = models.DeviceData(user=user_data, name=name).save()
         last_links = models.getUnreadLinks(device)
         channel = channels.Channel(device.address, False)
         for link in last_links:
             channel.queueLink(link)
         channel.send()
         stats.record("user_connected", simplejson.dumps({"user": user.email()}))
         self.response.out.write(device.address)
Example #41
0
def myprofile(request):
  form   = Form()
  fields = request.getForm()
  user   = users.get_current_user()
  uid    = user.user_id()

  # sanitize
  name  = utils.toStr(fields.get('username',''),80)
  nick  = utils.toStr(fields.get('nickname',''),40)
  email = utils.toStr(fields.get('email'   ,''),80)
  token = utils.toStr(fields.get('token'   ,''),80)
  userid= str(uid)
  if not name: name = 'Anonymous'
  
  # validate
  ok=True
  warn=[]
  if userid != token :
    warn.append('You need to login to change your profile')
    ok=False
  # TODO: check for duplicate nick
  if not nick:
    warn.append('Nickname can not be empty')
    ok=False
  if ok:
    data = {'userid':uid,'nickname':nick,'username':name,'email':email}
    rec  = models.saveUser(data)
    form.ok  = True
    form.url = '%s/myprofile'%(app.root)
    form.redirect = True
  else:
    form.ok   = False
    form.warn = warn
    form.data = {
      'profile':models.getUser(uid),
      'warn'   :warn
    }
  return form


#---- END ----
Example #42
0
    def post(self):
        id = get_user_id()
        q = models.getUser(id)
        creator = q.username
        explanation = self.request.get('explanation')
        if not explanation:
            explanation = "No Explanation Provided"
        category = self.request.get('category')
        question = self.request.get('questiontext')
        answer1 = self.request.get('answer1')
        answer2 = self.request.get('answer2')
        answer3 = self.request.get('answer3')
        answer4 = self.request.get('answer4')
        answerid = self.request.get('answerid')
        try:
            upload_files = self.get_uploads()
            blob_info = upload_files[0]
            type = blob_info.content_type

            # if the uploaded file is an image
            if type in ['image/jpeg', 'image/png', 'image/gif', 'image/webp']:
                image = blob_info.key()
                questionID = models.createQuestion(category,
                        question,answer1,answer2,answer3,answer4,answerid,
                        explanation,creator,False,image)

            # if the uploaded file is not an image
            else:
                questionID = models.createQuestion(category,
                        question,answer1,answer2,answer3,answer4,answerid,
                        explanation,creator,False)

            self.redirect('/NewQuestion?id=' + questionID.urlsafe())

        # no image to upload
        except IndexError:
            questionID = models.createQuestion(category,
                    question,answer1,answer2,answer3,answer4,answerid,
                    explanation,creator,False)

        self.redirect('/NewQuestion?id=' + questionID.urlsafe())
Example #43
0
 def post(self, name="Chrome"):
     self.response.headers.add_header("Access-Control-Allow-Origin", "*")
     user = auth.getCurrentUser()
     device = None
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except:
             device = models.DeviceData(user=user_data, name=name).save()
         last_links = models.getUnreadLinks(device)
         channel = channels.Channel(device.address, False)
         for link in last_links:
             channel.queueLink(link)
         channel.send()
         stats.record("user_connected",
                      simplejson.dumps({"user": user.email()}))
         self.response.out.write(device.address)
Example #44
0
 def get(self):
     questionID = self.request.get('id')
     id = get_user_id()
     review = models.getQuestionFromURL(questionID)
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 'upload_url': blobstore.create_upload_url('/profile'),
                 'user_email': get_user_email(),
                 'login_url': users.create_login_url(),
                 'logout_url': users.create_logout_url('/'),
                 'user_id': get_user_id(),
                 'profile': models.getUser(id),
                 'admin': is_admin
             }
             render_template(self, 'createProfile.html', page_params)
             return
     page_params = {
         'upload_urlQE':
         blobstore.create_upload_url('/ReviewQuestion?id=' + questionID),
         'user_email':
         get_user_email(),
         'login_url':
         users.create_login_url(),
         'logout_url':
         users.create_logout_url('/'),
         'user_id':
         id,
         'review':
         review,
         'admin':
         is_admin
     }
     render_template(self, 'reviewQuestion.html', page_params)
Example #45
0
 def post(self):
     self.response.headers.add_header("Access-Control-Allow-Origin", "*")
     user = auth.getCurrentUser()
     response = {}
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         name = self.request.get("name")
         if not name:
             name = "Chrome"
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except models.DeviceDoesNotExistError:
             device = models.DeviceData(name=name, user=user_data).save()
         receiver = None
         if self.request.get("receiver"):
             try:
                 receiver = models.getDevice("%s/%s" % (user.email(), self.request.get("receiver")))
             except models.DeviceDoesNotExistError:
                 receiver = models.DeviceData(name=self.request.get("receiver"), user=user_data).save()
         if receiver == None:
             receiver = device
         link = models.LinkData(url=self.request.get("link"), sender=device, receiver=receiver).save()
         if models.getQuota().amount >= models.getStats("channels").count or user_data.immune():
             channel = channels.Channel(receiver.address, False)
             channel.sendLink(link)
             response["code"] = 200
             response["link"] = link.url
         else:
             response["code"] = 503
             response["link"] = link.url
     else:
         response["code"] = 401
         response["link"] = self.request.get("link")
     self.response.out.write(simplejson.dumps(response))
Example #46
0
 def get(self):
     user = users.User("*****@*****.**")
     try:
         user_data = models.getUser(user)
     except models.UserDoesNotExistError:
         user_data = models.UserData(user=user).save()
     try:
         device = models.getDevice("%s/%s" % (user.email(), "Web"))
     except models.DeviceDoesNotExistError:
         device = models.DeviceData(user=user_data, name="Web").save()
     channel = channels.Channel(device.address, override_quota=True)
     path = os.path.join(os.path.dirname(__file__), "dashboard.html")
     stats_data = models.StatsData.all().order("-date").fetch(1000)
     template_values = {"channel_id": channel.token, "stats": {}}
     stats = template_values["stats"]
     for datapoint in stats_data:
         datestamp = int(time.mktime(datapoint.date.date().timetuple()) * 1000)
         hour = datapoint.date.hour
         if datestamp not in stats:
             stats[datestamp] = {"datestamp": datestamp, "date": datapoint.date, "datapoints": {}}
         if datapoint.datapoint not in stats[datestamp]["datapoints"]:
             stats[datestamp]["datapoints"][datapoint.datapoint] = {"datapoint": datapoint.datapoint, "values": {}}
         point_id = "%s" % hour
         if datapoint.duration == "day":
             point_id = "total"
         dp = datapoint.datapoint
         stats[datestamp]["datapoints"][dp]["values"][point_id] = {
             "datapoint": datapoint.datapoint,
             "datestamp": datestamp,
             "hour": hour,
             "count": int(datapoint.count),
             "duration": datapoint.duration,
         }
     template_values["stats"] = stats
     logging.info(template_values)
     self.response.out.write(template.render(path, template_values))
Example #47
0
 def get(self,uid):
   user = models.getUser(uid)
   data = {'user':user,'userid':uid}
   self.show('profile',data)
Example #48
0
 def post(self):
     record = prospective_search.get_document(self.request)
     record_value = simplejson.loads(record.value)
     subscriber_keys = map(db.Key, self.request.get_all('id'))
     subscribers = db.get(subscriber_keys)
     datapoints = []
     stats_json = []
     for subscriber_key, subscriber in zip(subscriber_keys, subscribers):
         if not subscriber:
             prospective_search.unsubscribe(stats.StatsRecord,
                                            subscriber_key)
         else:
             datapoints.append(
                 models.getStats(subscriber.datapoint,
                                 record.timestamp,
                                 duration='day'))
             datapoints.append(
                 models.getStats(subscriber.datapoint,
                                 record.timestamp,
                                 duration='hour'))
     for datapoint in datapoints:
         if datapoint.datapoint == 'active_users':
             try:
                 user = models.getUser(record_value['user'], False)
             except models.UserDoesNotExistError:
                 continue
             last_seen = user.last_seen
             new_last_seen = timestamp.now()
             if datapoint.duration == "day":
                 last_seen = last_seen.replace(hour=0,
                                               minute=0,
                                               second=0,
                                               microsecond=0)
                 new_last_seen = new_last_seen.replace(hour=0,
                                                       minute=0,
                                                       second=0,
                                                       microsecond=0)
             if last_seen < new_last_seen:
                 user.updateLastSeen(new_last_seen)
                 user.save()
             else:
                 continue
         if datapoint.datapoint == 'quota':
             datapoint.count = models.getQuota().amount
         else:
             datapoint.increment()
         json = {
             'datapoint': datapoint.datapoint,
             'value': datapoint.count,
             'date': datapoint.date.strftime("%D, %M %d %y"),
             'datestamp':
             int(time.mktime(datapoint.date.date().timetuple())) * 1000,
             'hour': datapoint.date.hour
         }
         if datapoint.duration == "day":
             json['hour'] = "total"
         stats_json.append(json)
     db.put(datapoints)
     push = channels.Channel("[email protected]/Web", False)
     push.message = {"stats": stats_json}
     push.send()
     logging.debug(simplejson.dumps(stats_json))
Example #49
0
def on_login_complete(data):
    # print("inside fb login")
    if data['fb_user_token']:
        loggedInFrom = 'Facebook'
        response = requests.get(
            'https://graph.facebook.com/v2.8/me?fields=id%2Cname%2Cpicture&access_token='
            + data['fb_user_token'])
        json = response.json()
        name = json['name']
        link = json['picture']['data']['url']

    elif data['google_user_token']:
        loggedInFrom = 'Google'
        response = requests.get(
            'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' +
            data['google_user_token'])
        json = response.json()
        name = (json['given_name'] + " " + json['family_name'])
        link = json['picture']
    welcome_message = bot.botResponses(
        ("!! say Everyone! " + name +
         " has finally come to the great city of Pawnee!!"))
    models.addMessage(1, bot.botID, welcome_message)
    all_messages = models.getChatMessages(1)
    if models.userExists(link):
        user = models.getUser(link)
        key = user['userID']
        join_room(key)
        print("*************************user*************", user)
        if key not in users_connected:
            users_connected[key] = user
        connectedList = list(users_connected.values())
        print("*************************connectedList*************",
              connectedList)
        print(len(connectedList))
        connectedCount = len(users_connected)
        socketio.emit('login success', {
            "isLoggedIn": 1,
            'loggedInFrom': loggedInFrom,
            'user': user,
            'messages': all_messages,
            'connected_users': connectedList,
            'numberOfUsers': connectedCount
        },
                      broadcast=True,
                      room=key)

    else:
        new_user = models.addUser(name, link)
        nu_ = models.getUserByID(new_user.userID)
        key = nu_['userID']
        join_room(key)
        print("*************************user*************", nu_)
        if key not in users_connected:
            users_connected[key] = nu_
        connectedList = list(users_connected.values())
        connectedCount = len(users_connected)
        socketio.emit('login success', {
            "isLoggedIn": 1,
            'loggedInFrom': loggedInFrom,
            'user': nu_,
            'messages': all_messages,
            'connected_users': connectedList,
            'numberOfUsers': connectedCount
        },
                      broadcast=True,
                      room=key)
Example #50
0
 def get(self, uid):
     user = models.getUser(uid)
     data = {'user': user, 'userid': uid}
     self.show('profile', data)