def user_auth_edit(username):
	error = ''
	try:
		reload(sys)
		sys.setdefaultencoding('utf-8')
		
		username=username
		c, conn = connection()
		if request.method == "POST":
			permit = request.values.get("user_auth")
		
			#Be carefule!! Must use [] to quote username , otherwise it will
			#prompt a warning like: "not all arguments converted during string formatting"
			c.execute("update users set auth_type='%s' where username='******'" % (permit,username) )
			conn.commit()
			
			c.close()
			conn.close()
			gc.collect()
			flash('user authorization updated successfully!')
			return  redirect(url_for('users_list'))
		else:
			c, conn = connection()
			c.execute("select * from users where username = (%s)", [username])
			auth_type_db = c.fetchone()[5] 
			return render_template("user-auth-edit.html", title=u'用户权限', auth_type_db=auth_type_db,username=username, error=error)
	
	except Exception as e:
		return str(e)
示例#2
0
def user_auth_edit(username):
	error = ''
	try:
		set_cn_encoding()
		username=username 
		c, conn = connection()
		if request.method == "POST":
			permit = (request.values.get("user_auth")).encode('utf-8')
		
			#Be carefule!! Must use [] to quote username , otherwise it will
			#prompt a warning like: "not all arguments converted during string formatting"
			c.execute("update login_user set auth_type='%s' where username='******'" % (permit,username) )
			conn.commit()
			
			c.close()
			conn.close()
			gc.collect()
			flash(u'用户权限更新成功!')
			return  redirect(url_for('users_list'))
		else:
			c, conn = connection()
			c.execute("select * from login_user where username = (%s)", [username])
			auth_type_db = c.fetchone()[5] 
			
			#Get number of logs/login_user/docs and display them with "bootstrap badge"
			num_logs = (sysadm_badges_number())[0]
			num_users = (sysadm_badges_number())[1]
			num_docs = (sysadm_badges_number())[2]
			
			return render_template("user-auth-edit.html", title=u'修改权限', auth_type_db=auth_type_db,username=username,
			num_logs=num_logs, num_users=num_users, num_docs=num_docs, error=error)
	
	except Exception as e:
		return str(e)
def main():
    form = RegistrationForm(request.form)
    try:
        c,conn = connection()
        error = None
        if request.method == 'POST':
            try:
                data = c.execute("SELECT * FROM users WHERE username = (%s)",
                        thwart(request.form['username']))
                data = c.fetchone()[2]

                if sha256_crypt.verify(request.form['password'], data):
                    session['logged_in'] = True
                    session['username'] = request.form['username']
                    flash('You are now logged in.')
                    return redirect(url_for('dashboard'))
            except Exception, e:
                flash("What are you doing?")


            try:
                
                if request.method == 'POST' and form.validate():

                    username = form.username.data
                    email = form.email.data

                    password = sha256_crypt.encrypt((str(form.password.data)))
                    c,conn = connection()

                    x = c.execute("SELECT * FROM users WHERE username = (%s)",
                        (thwart(username)))

                    if int(x) > 0:
                        flash("That username is already taken, please choose another")
                        return render_template('register.html', form=form)

                    else:
                        c.execute("INSERT INTO users (username, password, email) VALUES (%s, %s, %s)",
                            (thwart(username), thwart(password), thwart(email)))
                        conn.commit()
                        flash('Thanks for registering')
                        c.close()
                        conn.close()
                        gc.collect()
                        session['logged_in'] = True
                        session['username'] = username
                        return redirect(url_for('dashboard'))

            except Exception as e:
                return(str(e))
  
            else:
                flash('Invalid credentials. Try again')
        gc.collect()
        return render_template("main.html", error=error, form=form, page_type = "main")
def register_page():
    
    try:
        form = RegistrationForm(request.form)

        if request.method == "POST" and form.validate():
            username = form.username.data
            email = form.email.data
            password = sha256_crypt.encrypt(str(form.password.data))
            c, conn = connection()
            ret = c.execute("SELECT * FROM users WHERE username = ('{0}');".format(thwart(username)))

            if int(ret) > 0:    
                return "Username taken"

            else:
                c.execute("INSERT INTO users (username, password, email) VALUES ('{0}', '{1}', '{2}')".format(thwart(username), thwart(password), thwart(email)))
                conn.commit()
                c.close() #Close db connection, saves ram
                conn.close()

                gc.collect()

                session["logged_in"] = True
                session["username"] = username
                
                return redirect(url_for("dashboard"))

        return render_template("register.html", form = form)

        

    except Exception as e:
        return str(e)
def login_page():

    error = None

    try:

        #Already logged in
        if "logged_in" in session:
            return redirect(url_for("dashboard"))

        #Else, establish db connection
        c, conn = connection()
        if request.method == "POST":
            
            data = c.execute("SELECT * FROM users WHERE username = ('{0}');".format(thwart(request.form["username"])))
            data = c.fetchone()[2] #password

            if sha256_crypt.verify(request.form["password"], data):
                session["logged_in"] = True
                session["username"] = request.form["username"]

                return redirect(url_for("dashboard"))

            else:
                error = "Invalid credentials, try again."

        c.close() #Close db connection, saves ram
        gc.collect()

        return render_template("login.html", error = error)

    except Exception as e:
        error = "Invalid credentials, try again. {0}".format(str(e))
        return render_template("login.html", error = error)
示例#6
0
def deltask(task_id):
	c,conn=connection()
	c.execute("DELETE FROM tb_tasks WHERE id=%d"%(task_id))
	conn.commit()
	c.close()
	conn.close()
	return redirect(url_for('tasks'))
示例#7
0
def rest_users():
	try:
		response=[]
		data={}

		json_data=""
		c, conn = connection()			
		c.execute("SELECT uid,username,name,surname,telephone,email,authority FROM tb_users ")
		rows = c.fetchall()
			
		for item in rows:
			data['ID']=item[0]
			data['name']=item[2]
			data['surname']=item[3]
			data['telephone']=item[4]
			data['email']=item[5]
			data['authority']=item[6]

			json_data=json_data + json.dumps(data)
				
		c.close()
		conn.close()

		return ('{"user":['+json_data+"]}")

	except Exception as e:
		return(str(e))
示例#8
0
def activity():
	error=''
	i=0
	try:
		data={}
		values=[]
		ACTIVITY_LIST=[]
			
		c, conn = connection()	
		c.execute("SELECT tb_users.username, tb_device.name, tb_activity.prevstatus, tb_activity.currentstatus,tb_activity.IP,tb_activity.DATE,tb_activity.error,tb_activity.report FROM tb_users, tb_activity, tb_device WHERE tb_users.uid=tb_activity.user_id and tb_device.id=tb_activity.device_id ")
		rows = c.fetchall()
		
		for row in rows:			
			data["Username"]=row[0]
			data["Device"]=row[1]
			data["Prevstatus"]=row[2]
			data["Currentstatus"]=row[3]
			data["IP"]=row[4]
			data["DATE-TIME"]=row[5]
			data["Error"]=row[6]
			data["Report"]=row[7]
							
			ACTIVITY_LIST.insert(i,data)
			data={}
			i=i+1
			
		c.close()
		conn.close()
		return render_template("activity.html",ACTIVITY_LIST=ACTIVITY_LIST) 	

	except Exception as e:
		flash(e)
示例#9
0
def news():
	try:
		c, conn = connection()
		data1 = c.execute("SELECT username FROM photos")
		data1 = c.fetchall()
		data2 = c.execute("SELECT description FROM photos")
		data2 = c.fetchall()
		data3 = c.execute("SELECT link FROM photos")
		data3 = c.fetchall()
		users = []
		descs = []
		links = []
		for i in data1:
			users.append(str(i).strip("(),'"))
		for i in data2:
			descs.append(str(i).strip("(),'"))
		for i in data3:
			links.append(str(i).strip("(),'"))
		users.reverse()
		descs.reverse()
		links.reverse()
		print users
		print descs
		return render_template("news.html", usersdescslinks = zip(users,descs,links), username = session["username"], loggedIn = session["logged_in"])
	except Exception as e:
		return str(e)
示例#10
0
def userlist():
	error=''
	i=0
	try:
		data={}
		USER_LIST=[]
			
		c, conn = connection()	
		c.execute("SELECT uid,username,name,surname,email,telephone,authority,active FROM tb_users ")
		rows = c.fetchall()
		
		for row in rows:			
			data["ID"]=row[0]
			data["username"]=row[1]
			data["name"]=row[2]
			data["surname"]=row[3]
			data["email"]=row[4]
			data["telephone"]=row[5]
			data["authority"]=row[6]
			data["active"]=row[7]
							
			USER_LIST.insert(i,data)
			data={}
			i=i+1
			
		c.close()
		conn.close()
		return render_template("list.html",USER_LIST=USER_LIST) 	

	except Exception as e:
		flash(e)
示例#11
0
def devices():
	try:
		i=0
		data={}
		DEVICE_LIST=[]
		c, conn = connection()
		c.execute("SELECT * FROM tb_device ")
		rows = c.fetchall()
		for row in rows:			
			data["ID"]=row[0]
			data["name"]=row[1]
			data["location"]=row[2]
			data["status"]=row[3]
			data["active"]=row[4]
							
			DEVICE_LIST.insert(i,data)
			data={}
			i=i+1
			
		c.close()
		conn.close()
		
		return render_template("device.html",DEVICE_LIST=DEVICE_LIST) 
		
	except Exception as e:
		return str(e)
示例#12
0
def login_page():
	error = ''
	try:
		c, conn = connection()
		if request.method == "POST":
			data = c.execute("select * from users where username = (%s)", [thwart(request.form['username'])])
			
			#get the first record
			data = c.fetchone()[2]
			
			#check if password matches
			if sha256_crypt.verify(request.form['password'], data):
				session['logged_in'] = True
				session['username'] = request.form['username']
				
				flash("You are now logged in!")
				return redirect(url_for('dashboard'))
				
			else:
				error = "Invalid credentials, try again!"
		
		gc.collect()	
		
		return render_template("login.html", error=error)
		
	except Exception as e:
		error = "Invalid credentials, try again!"
		return  render_template("login.html", error = error)
示例#13
0
def sysadm_badges_number():
	try:
		#Get number of logs and display it with "bootstrap badge"
		loglist = []
		for logfile in os.listdir(LOGS_PATH):
			loglist.append(logfile)
		num_logs = len(loglist)
		
		#Get number of users and display it with "bootstrap badge"
		c, conn = connection()
		c.execute("SELECT * from login_user;")
		num_users = int(c.rowcount)
		
		#Get number of docs and display it with "bootstrap badge"
		num_docs = sum([len(files) for root,dirs,files in os.walk(DOCS_PATH)])
		
		#Get number of weekly whiteboards and display it with "bootstrap badge"
		wblist = []
		for weeklyfile in os.listdir(WEEKLY_PATH):
			wblist.append(weeklyfile)
		num_weeklys = len(wblist)
		
		return(num_logs, num_users, num_docs, num_weeklys)
	except Exception as e:
		return str(e)
示例#14
0
def register_page():
	try:
		form = RegistrationForm(request.form)
		if request.method == "POST" and form.validate():
			username = form.username.data
			password = sha256_crypt.encrypt((str(form.password.data)))
			email = form.email.data
			c, conn = connection()

			x = c.execute("SELECT * FROM users WHERE username = %s", (username,))

			if int(x) > 0:
				flash("That username is already taken, please choose another")
				return render_template('register.html', form=form)

			else:
				c.execute("INSERT INTO users (username, password, email) VALUES (%s, %s, %s)",
			          (thwart(username), thwart(password), thwart(email)))

				conn.commit()
				flash("Thanks for registering!")
				c.close()
				conn.close()
				gc.collect()

		
				session['logged_in'] = True
				session['username'] = username

				return redirect(url_for('board'))

		return render_template("register.html", form=form)
		
	except Exception as e:
		return(str(e))
示例#15
0
def get_user_id(username):
    """Convenience method to look up the id for a username."""
    c,conn = connection()
    user_id = c.execute("SELECT uid FROM users WHERE username = %s", session['username'])
    user_id = c.fetchone()[0]

    return user_id
示例#16
0
def login():
	try:
		errorLog = ''
		errorReg = ''
		formLog = LoginForm(request.form)
		formReg = RegistrationForm(request.form)
		if request.method == "POST":
			#print "Hello"
			username = formLog.username.data
			password = formLog.password.data
			#print username, password
			c, conn = connection()
			data = c.execute("SELECT * FROM users WHERE username = (%s)",(thwart(username)))
			data = c.fetchone()[2]
			uid = c.execute("SELECT * FROM users WHERE username = (%s)",(thwart(username)))
			uid = c.fetchone()[0]
			#print "hello",data, uid
			#print "Hello"
			if sha256_crypt.verify(password, data):
				session['uid'] = uid
				session['logged_in'] = True
				session['username'] = username
				gc.collect()
				return redirect(url_for("news"))
				#return render_template("test.html", username = session["username"], loggedIn = session["logged_in"])
			else:
				errorLog = "Invalid Credentials"
				return render_template('home.html', formLog = formLog, formReg = formReg, errorLog = errorLog, errorReg = errorReg)
	except Exception as e:
		errorLog = "Invalid credentials"
		return render_template ("home.html", formLog = formLog, formReg = formReg, errorLog = errorLog, errorReg = errorReg)
示例#17
0
def register():
	try:
		errorLog = ''
		errorReg = ''
		formReg = RegistrationForm(request.form)
		formLog = LoginForm(request.form)
		if request.method == "POST" and formReg.validate():
			username = formReg.username.data
			email = formReg.email.data
			password = sha256_crypt.encrypt((str(formReg.password.data)))
			c, conn = connection()
			x = c.execute("SELECT * FROM users WHERE username = (%s)",(thwart(username)))
			if int(x) > 0:
				errorReg = "That username is taken."
				print("That username is already taken please choose another")
				return render_template("home.html", formReg = formReg, formLog = formLog, errorLog = errorLog, errorReg = errorReg)
			else:
				c.execute("INSERT INTO users (username, password, email) VALUES (%s, %s, %s)",
				(thwart(username),thwart(password),thwart(email)))
				uid = c.execute("SELECT uid FROM users WHERE username = (%s)",(thwart(username)))
				conn.commit()
				c.close()
				conn.close()
				gc.collect()
				session["uid"]=uid
				session["logged_in"] = True
				session["username"] = username
				return redirect(url_for("news"))
	except Exception as e:
		return str(e)
示例#18
0
def login():
	error = ""
	try:
		if request.method == 'POST':
			c, conn = connection()

			data = c.execute("SELECT * FROM data WHERE username = (%s)", thwart(str(request.form['username'])))
			data = c.fetchone()[3]

			if sha256_crypt.verify(str(request.form['password']), str(data)):
				session['logged_in'] = True
				session['username'] = request.form['username']
				c.close()
				conn.close()
				gc.collect()
				flash('Logged in Successfully')
				return redirect(url_for('show_vault'))

			else:
				error = "Invalid Credentials"
				return render_template("login.html", error=error)

		return render_template("login.html", error=error)

	except Exception as e:
		error = "Invalid Credentials" #str(e)
		return render_template('login.html', error=error)
示例#19
0
def enter_vault():
	error = ""
	if 'logged_in' in session:
		form = vaultForm(request.form)

		if request.method == 'POST' and form.validate():
			title = form.title.data
			username = form.username.data
			password = form.password.data

			c, conn = connection()

			c.execute("INSERT INTO "+ str(session['username']).lower() + " (title, username, password) VALUES (%s, %s, %s)", (thwart(title), thwart(username), thwart(password)))
			conn.commit()
			c.close()
			conn.close()
			gc.collect()
			flash("Data Entered Succesfully")
			#return redirect(url_for('index'))
			return redirect(url_for('show_vault'))

		else:
			error = "Fill out all details"
			return render_template('enter_vault.html', error=error, form=form)

	else:
		flash("You need to login first")
		return redirect(url_for('login'))
示例#20
0
文件: main.py 项目: jk34/Python_Flask
def login_page():
    print "login page"
    error = ''
    try:
        c, conn = connection()
        if request.method == "POST":
	    print "login POST"
            data = c.execute("SELECT * FROM users WHERE username = (%s)",
                             [thwart(request.form['username'])] )
	    
            if not data:
		flash('username does not exist')
            data = c.fetchone()[2]
	    print "data fetchone"
            if sha256_crypt.verify(request.form['password'], data):
                session['logged_in'] = True
                session['username'] = request.form['username']

                flash('You are now logged in')
                return redirect(url_for("dashboard"))

            else:
		flash('incorrect password')
                e = "Invalid credentials, try again."

        gc.collect()

        return render_template("login.html", error=error)

    except Exception as e:
        print e
        error = "EXCEPTIONInvalid credentials, try again."
        return render_template("login.html", error = error)  
def update_user_tracking():
    try:
        completed = str(request.args['completed'])
        if completed in str(TOPIC_DICT.values()):
            client_name, settings, tracking, rank = userinformation()
            if tracking == None:
                tracking = completed
            else:
                if completed not in tracking:
                    tracking = tracking+","+completed
            
            c,conn = connection()
            c.execute("UPDATE users SET tracking = %s WHERE username = %s",
                    (thwart(tracking),thwart(client_name)))
            conn.commit()
            c.close()
            conn.close()
            client_name, settings, tracking, rank = userinformation()

        else:
            pass

            
    except Exception, e:
        pass
示例#22
0
def login_page():
    error = ''
    try:
        c, conn = connection()
        if request.method == "POST":

            data = c.execute("SELECT * FROM users WHERE username = (%s)",
                             thwart(request.form['username']))
            
            data = c.fetchone()[2]

            if sha256_crypt.verify(request.form['password'], data):
                session['logged_in'] = True
                session['username'] = request.form['username']

                flash("You are now logged in")
                return redirect(url_for("dashboard"))

            else:
                error = "Invalid credentials, try again."

        gc.collect()

        return render_template("login.html", error=error)

    except Exception as e:
        error =  flash(e)
        #error = "Invalid credentials, try again."
        return render_template("login.html", error = error)  
示例#23
0
def newPID():
    try:
        form = NewPersonIDCard(request.form)
        if request.method == "POST":
            c,conn = connection()
            x = c.execute("INSERT INTO personalkort (fornavn, etternavn, telefon, firma, leder, type, serienr, legitimasjon, sykkelbod, arkiv, boder, tsst, opm) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                          (thwart(request.form['fornavn']),
                           thwart(request.form['etternavn']),
                           thwart(request.form['telefonnummer']),
                           thwart(request.form['firma']),
                           thwart(request.form['leder']),
                           thwart(request.form['korttype']),
                           thwart(request.form['serienummer']),
                           thwart(request.form['kode']),
                           thwart(request.form['sykkelbod']),
                           thwart(request.form['arkiv']),
                           thwart(request.form['boder']),
                           thwart(request.form['tsst']),
                           thwart(request.form['opm'])))
            conn.commit()
            conn.close()
            if x == 1:
                flash("Brukeren er registrert")
            else:
                flash("Error")
    except Exception as e:
        return (str(e))
    return render_template('newpersonid.html', form=form)
示例#24
0
def mealplan():
        c, conn = connection() 
        c.execute("INSERT INTO mealplan (countMeal) VALUES (35)")
        a = str(c.lastrowid)
        c.execute("SELECT meal_id FROM meal WHERE type = 'B' ORDER BY RAND() LIMIT 7 ")
        breakfasts = c.fetchall()
        c.execute("SELECT meal_id FROM meal WHERE type = 'L' ORDER BY RAND() LIMIT 7 ")
        lunch = c.fetchall()
        c.execute("SELECT meal_id FROM meal WHERE type = 'D' ORDER BY RAND() LIMIT 7 ")
        dinner = c.fetchall()
        c.execute("SELECT meal_id FROM meal WHERE type = 'S' ORDER BY RAND() LIMIT 14 ")
        snacks = c.fetchall()
        i = 0
        u= 0
        y=0
        t=0
        while i <= (len(snacks))-1:
            snack = str(snacks[i][0])
            
            #c.execute("INSERT INTO generates(mealplan_id,meal_id) VALUES (%d,%s)", 1,snacks[i][0])
            c.execute("INSERT INTO generates (meal_id,mealplan_id) VALUES (%s, %s)",(int(snack),a))
            i += 1
        while u <= (len(dinner))-1:
            dinner = str(dinner[u][0])
            c.execute("INSERT INTO generates (meal_id,mealplan_id) VALUES (%s, %s)",(int(dinner),a))
            u+=1
        while y <= (len(lunch))-1:
            lunch = str(lunch[y][0])
            c.execute("INSERT INTO generates (meal_id,mealplan_id) VALUES (%s, %s)",(int(lunch),a))
            y+=1
        while t <= (len(breakfasts))-1:
            breakfast = str(breakfasts[t][0])
            c.execute("INSERT INTO generates (meal_id,mealplan_id) VALUES (%s, %s)",(int(breakfast),a))
            t+=1
        return "str(breakfast[t][0])"
示例#25
0
def doc_network_dashboard():	
	c, conn = connection()
	#Be carefule!! Must use [] to quote session['username'] , otherwise it will
	#prompt a warning like: "not all arguments converted during string formatting"
	c.execute("select * from login_user where username = (%s)", [session['username']])
	
	#get the auth_type of first record
	auth_type_db = c.fetchone()[5]
	
	#check if auth_type matches
	if 'net' == auth_type_db or 'adm' == auth_type_db or 'superadm' == auth_type_db:
		set_cn_encoding()
		write_log_info('network')
		
		doclist = []
		for docfile in os.listdir(NETWORK_DOCS_PATH):
			doclist.append(docfile)
		
		#Get number of docs of network
		num_network = (docs_badges_number())[1]	
		
		return  render_template("doc-network-dashboard.html", title=u'网络岗文档库', num_network=num_network,doclist = doclist)	
	else:
		write_log_info('networkDenied')
		return redirect(url_for('role_error_page'))	
示例#26
0
def doc_server_dashboard():	
	c, conn = connection()
	#Be carefule!! Must use [] to quote session['username'] , otherwise it will
	#prompt a warning like: "not all arguments converted during string formatting"
	c.execute("select * from login_user where username = (%s)", [session['username']])
	
	#get the auth_type of first record
	auth_type_db = c.fetchone()[5]
	
	#check auth_type of the logged in user, if not matches, redirect to role_error_page
	if 'ser' == auth_type_db or 'adm' == auth_type_db or 'superadm' == auth_type_db:
		set_cn_encoding()
		write_log_info('server')
		
		doclist = []
		for docfile in os.listdir(SERVER_DOCS_PATH):
			doclist.append(docfile)

		#Get number of docs of server
		num_server = (docs_badges_number())[0]	
			
		return  render_template("doc-server-dashboard.html", title=u'服务器岗文档库', num_server=num_server,doclist = doclist)
	else:
		write_log_info('serverDenied')
		return redirect(url_for('role_error_page'))	
示例#27
0
	def create_excel(self):
		c, conn = connection()
		c.execute("INSERT INTO invoice_detail (invoice_number, part_number, purchase_order_number, shelf_location, status, claimed) VALUES ( '%s', '%s', '%s', '', '%s', '%s' )" % ( thwart(self.invoice_number), thwart(self.part_number), thwart(self.purchase_order_number), thwart(self.status), thwart(self.claimed) ) )
		conn.commit()
		c.close()
		conn.close()
		gc.collect()
		return True
示例#28
0
	def get_shelves():
		c, conn = connection()
		c.execute("SELECT DISTINCT shelf_location FROM invoice_detail")
		all_shelves = c.fetchall()
		c.close()
		conn.close()
		gc.collect()
		return all_shelves
示例#29
0
	def create(self):
		c, conn = connection()
		c.execute("INSERT INTO invoice (invoice_number, date_received) VALUES ( '%s', '%s' )" % (thwart(self.invoice_number), thwart(self.date_received) ) )
		conn.commit()
		c.close()
		conn.close()
		gc.collect()
		return True
示例#30
0
	def get_by_part_number(part_number):
		c, conn = connection()
		c.execute("SELECT * FROM part_detail WHERE part_number = '%s'" % (thwart(part_number) ))
		part_detail = c.fetchone()
		c.close()
		conn.close()
		gc.collect()
		return part_detail
示例#31
0
def signup():
    try:
        form = RegistrationForm(request.form)

        if request.method == "POST":
            username = request.form['username']
            first_name = request.form['firstname']
            last_name = request.form['lastname']
            email = request.form['email']
            pass1 = request.form['password']
            pass2 = request.form['password2']

            password = sha256_crypt.encrypt((str(pass1)))

            c, conn = connection()

            x = c.execute("SELECT * FROM users2 WHERE username = (%s)", [
                thwart(username),
            ])

            if int(x) > 0:
                flash("That username is already taken, please choose another")
                return render_template('html/signup.html')

            else:
                c.execute(
                    "INSERT INTO users2 (username, password, first_name, last_name, email) VALUES (%s, %s, %s, %s, %s)",
                    [
                        thwart(username),
                        thwart(password),
                        thwart(first_name),
                        thwart(last_name),
                        thwart(email),
                    ])

                conn.commit()
                flash("Thanks for registering!")
                c.close()
                conn.close()
                gc.collect()

                session['logged_in'] = True
                session['username'] = username

                return redirect(url_for('home'))

        return render_template("html/signup.html")

    except Exception as e:
        return (str(e))
示例#32
0
def load_user(id):
    c,conn = connection()
    data = c.execute("SELECT * FROM users WHERE uid = (%s)",
                            [thwart(id)])
    if int(data) == 0:
        return None
    row = c.fetchone()
    data = row[2]
    username = row[1]
    uid = row[0]
    c.close()
    conn.close()
    gc.collect()
    return User(username,uid)
示例#33
0
文件: parse.py 项目: gjkcz/Klozet
def open_times_to_db(toilet_id, open_times_dict):
    c, conn = connection()
    for open_times in open_times_dict:
        days_dict = get_days_dict(open_times["days"])
        nonstop = is_nonstop(open_times)
        hours = get_hours(open_times)
        sql = "INSERT INTO `open_times` (`toilet_id`, `start_time`, `close_time`, `mon`, `tue`, `wed`, `thu`, `fri`, `sat`, `sun`, `nonstop`) VALUES ((SELECT `toilet_id` FROM `toilets` WHERE `toilet_id` = %s LIMIT 1), %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
        c.execute(
            sql,
            (toilet_id, hours[0], hours[1], days_dict["mon"], days_dict["tue"],
             days_dict["wed"], days_dict["thu"], days_dict["fri"],
             days_dict["sat"], days_dict["sun"], nonstop))
    conn.commit()
    conn.close()
示例#34
0
def users_list():
    try:
        c, conn = connection()

        #get all users
        c.execute(
            "select `username`, `auth_type`, `email`, `regdate`  from users")
        users_db = c.fetchall()

        return render_template("users-list.html",
                               title=u'用户列表',
                               users_db=users_db)
    except Exception as e:
        return str(e)
示例#35
0
文件: netpop.py 项目: ashoover/NetPop
    def host_list():
        try:
            c, conn = connection()
            c.execute("SELECT last_check, endpoint_status, endpoint_name FROM netpop.endpoints;")

            results = c.fetchall()

            c.close()
            conn.close()

        except Exception:
            results = 'e'

        return results
示例#36
0
def user_load(user_id):
    try:
        con, conn = connection()
        con.execute("SELECT * FROM user WHERE id_user = (%s)",
                    escape_string(str(user_id)))
        user_dict = con.fetchone()
        user = User()
        user.update(user_dict)
        con.close()
        conn.close()
        gc.collect()
        return user
    except:
        return None
示例#37
0
文件: netpop.py 项目: ashoover/NetPop
def edit_endpoint():
    try:
        c, conn = connection()
        c.execute("SELECT endpoint_name, endpoint_status FROM netpop.endpoints;")

        results = c.fetchall()

        c.close()
        conn.close()

        return render_template("edit_endpoint.html", ehost_l=results)

    except Exception as e:
        return render_template("error.html", error=e)
示例#38
0
文件: netpop.py 项目: ashoover/NetPop
def endpoint(endpoint_name):
    try:
        c, conn = connection()
        c.execute("SELECT * FROM netpop.endpoints WHERE endpoint_name LIKE %s", endpoint_name)

        results = c.fetchone()

        c.close()
        conn.close()

        return render_template("endpoint.html", endpoint_info=results)

    except Exception as e:
        return render_template("error.html", error=e)
示例#39
0
def threads():
    c, conn = connection()
    c.execute("SELECT * FROM posts ORDER BY post_posted DESC LIMIT 5")
    posts = c.fetchall()
    ids = [post[0] for post in posts]
    users = [post[1] for post in posts]
    bodies = [post[2] for post in posts]
    data = zip(ids, users, bodies)

    return render_template('threads.html',
                           ids=ids,
                           users=users,
                           bodies=bodies,
                           data=data)
示例#40
0
def login():
    c, conn = connection()
    c.execute("SELECT * FROM admin")
    data = c.fetchall()
    if request.method == 'POST':
        session.pop('admin', None)
        for i in data:
            if i[0] == request.form['email'] and i[1] == request.form[
                    'password']:
                session['admin'] = request.form['email']
                return redirect(url_for('dashboard_admin'))
        flash(f'Wrong Email or Password!', 'danger')
        return redirect(url_for('login'))
    return render_template("login.html")
示例#41
0
def ipLink():
    form = ipLinkForm(request.form)
    try:
        if request.method == 'POST' and form.validate():
            ipLink = form.ipLink.data
            mycursor, mydb = connection()
            mycursor.execute("INSERT INTO linksespecificos(ALVO) VALUES ('" +
                             str(ipLink) + "')")
            mydb.commit()
            flash("LINK/IP inserido com sucesso")
            mycursor.close()
            mydb.close()
            return redirect(url_for("getIpLink"))

        else:
            mycursor2, mydb2 = connection()
            mycursor2.execute('SELECT ALVO FROM linksespecificos')
            data = mycursor2.fetchall()
            mycursor2.close()
            mydb2.close()
            return render_template("getIpLink.html", listaIpLinks=data)
    except Exception as e:
        return (str(e))
def dashboard():
    recent = {}
    mrecent = []
    precent = []
    c, conn = connection()
    rece = c.execute(
        "select distinct(mname),plot from movies order by STR_TO_DATE(r_date,'%e %b %Y') desc LIMIT 10"
    )
    for i in range(0, int(rece)):
        x = c.fetchone()
        recent[x[0]] = x[1]
        #mrecent=x[0]
        #precent=x[1]
    return render_template("dashboard.html", recent=recent)
示例#43
0
def get_player_id_by_name(player_name):
    c, conn = db.connection()

    cmd_get_id_by_name = "SELECT PlayerID" \
                         " FROM Players " \
                         "WHERE PlayerName = '{:s}'"\
                         .format(player_name)

    c.execute(cmd_get_id_by_name)

    player_id = c.fetchone()
    player_id = player_id[0]

    return player_id
示例#44
0
def host_list():
    try:
        c, conn = connection()
        c.execute("SELECT ip FROM netpop.endpoints WHERE enabled = 1;")

        results = [item[0] for item in c.fetchall()]

        c.close()
        conn.close()

    except Exception:
        results = 'e'

    return results
示例#45
0
def edit_item(user_id, item_id):
    conn, cursor = connection(app)
    try:
        cursor.execute('SELECT * FROM Cart WHERE user_id="{}"'.format(user_id))
        data = cursor.fetchall()
        if data:
            elements = []
            for i in range(1, 8):
                element = {
                    "title": str(i),
                    "url": "{}/update_item/{}/{}/{}".format(link, user_id, item_id, i),
                    "type": "json_plugin_url"
                }
                elements.append(element)

            send = {
                "messages": [
                    {
                        "text":  "How many would you like to add?",
                        "quick_replies": elements
                    }
                ]
            }
            return jsonify(send)
        else:
            send = {
                "messages": [
                    {
                    "text": "There is nothing in your cart",
                    "quick_replies": [
                        {
                            "title": "Main menu",
                            "block_names": ["menu"]
                    }]
                    }
                ]
            }
            return jsonify(send)
    except Exception as e:
        print(e)
        cursor.close()
        conn.close()
    send = {
        "messages": [
            {
            "text": "Some Error Occured."
            }
        ]
    }
    return jsonify(send)
示例#46
0
def newadmin():
    data = request.get_json()
    username = data['username']
    name = data['name']
    password = data['password']
    try:
        cursor, conn = connection()
        sql = "insert into admins values(%s , %s , %s)"
        cursor.execute(sql, (username, name, password))
        conn.commit()
        conn.close()
        return jsonify({"status": 'admin added'})
    except:
        return jsonify({"status": 'Already exists'})
示例#47
0
文件: app.py 项目: iojas/GLBRC-Flask
def showAll():
    if 'user' in session:
        currentUser = session['user']
        c, conn = connection()
        c.execute(
            "select a.name,description,color from userApp as u inner join application as a on u.name=a.name and id=%s",
            [currentUser])
        data = c.fetchall()
        l = []
        for x in data:
            l.append(x)
        return render_template('showApp.html', apps=l)
    else:
        return render_template('showApp.html', warn='Please Log In')
示例#48
0
def fetchstudents(COLUMN_NAME):
    cursor, conn = connection()
    sql = "select a.usn , b.name , a.{0} from studentsdata a , credentials b where a.{0} <> 'no' and a.usn = b.userid".format(
        COLUMN_NAME)
    cursor.execute(sql)
    rows = [x for x in cursor]
    cols = [x[0] for x in cursor.description]
    ds = []
    for row in rows:
        d = {}
        for prop, val in zip(cols, row):
            d[prop] = val
        ds.append(d)
    return jsonify(ds)
示例#49
0
def activate_brands():
    try:
        c, conn = connection()
        idstring = request.form["beer_ids"]

        idarray = idstring.split(",")
        for element in idarray:
            beer_count = c.execute(
                "UPDATE beer_brands SET active=1 WHERE id=" + element)
        conn.commit()

        return jsonify({"epc": idarray})
    except Exception as e:
        return jsonify({"error": e})
示例#50
0
def login_page():
    error = ''
    try:
        c, conn = connection()
        if request.method == "POST":

            data = c.execute(
                "SELECT * FROM users WHERE username = '******'".format(
                    thwart(request.form['username'])))

            data = c.fetchone()[2]

            kd = pd.read_csv("/var/www/FlaskApp/data.csv")
            subjects = kd["subject"].unique()
            subject = subjects[2]
            vector = kd.loc[kd.subject == subject,
                            "H.period":"H.Return"].iloc[34].values
            pv = prepare_data(kd, subject)
            d = model(pv[0],
                      pv[2],
                      pv[1],
                      pv[3],
                      num_iterations=4000,
                      learning_rate=0.05,
                      print_cost=False)
            arr = np.array([vector, vector])
            lr_res = predict(d['w'], d['b'], arr.transpose())
            sc = StatisticClassifier(kd, 0.95)
            sc_res = sc.singleClassification(kd, vector)

            if (sha256_crypt.verify(request.form['password'], data)) and (
                (lr_res[0, 0] + sc_res) / 2 > 0.5):
                session['logged_in'] = True
                session['username'] = request.form['username']

                flash("You are now logged in")
                return redirect(url_for("reg"))

            else:
                error = "Invalid credentials, try again."

        gc.collect()

        return render_template("login.html", error=error)

    except Exception as e:
        flash(e)
        error = "Invalid credentials, try again."
        return render_template("login.html", error=error)
示例#51
0
def insert_usuario():
    try:
        if request.method == "POST":
            c, conn = connection()
            nome = request.form['nome']
            email = request.form['email']
            password = sha256_crypt.encrypt((str(request.form['password'])))
            print(nome)
            print(email)
            print(password)
            #print(confirme_password)
            x = c.execute("""
                            SELECT
                                *
                            FROM
                                usuarios
                            WHERE
                               email=%s""", [email])
            if int(x) > 0:
                flash("E-mail já está cadastrado. Verifique se está correto o email.")
                return render_template('register.html')
            if int(x) == 0:
                if sha256_crypt.verify(request.form['confirme_password'],password):
                    pontos = 0
                    c.execute("""
                    INSERT INTO
                          portifolio.usuarios
                             (nome,email,password,pontos)
                             VALUES
                              (%s,%s,%s,%s)""",
                          [nome, email, password, pontos])
                    flash("Obrigado por Registrar")
                    session['logged_in'] = True
                    session['username'] = nome
                    session['email'] = email
                    session['notificacoes'] = 0
                    session['pontos'] = 0
                    conn.commit()
                    c.close()
                    conn.close()
                    gc.collect()
                    flash("Cliente Cadastrado com Sucesso")
                    return render_template('teste.html')
                else:
                    flash("Passwords diferentes, insira novamente")
                    return render_template('register.html')
            return render_template('register.html')
    except Exception as e:
        return (str(e))
示例#52
0
def register():
    next_url = request.args.get('next')
    if not current_user.is_authenticated:
        try:
            if request.method == "POST":
                con, conn = connection()
                form = request.form
                email = form['email']
                password = sha256_crypt.encrypt((str(form['password'])))
                used_username = con.execute(
                    "SELECT * FROM user WHERE login = (%s)",
                    escape_string(request.form['login']))
                if "@" not in email:
                    wrong_email = True
                else:
                    wrong_email = False
                if used_username or wrong_email:
                    return render_template('register.html',
                                           form=form,
                                           used_username=used_username,
                                           wrong_email=wrong_email)
                con.execute(
                    "INSERT INTO scout (first_name, last_name) VALUES (%s, %s)",
                    (escape_string(
                        form['first-name']), escape_string(form['last-name'])))
                conn.commit()
                scout_id = con.lastrowid
                sql = "INSERT INTO user (login, password, email, scout_id) VALUES (%s, %s, %s, " + str(
                    scout_id) + ")"
                con.execute(
                    sql,
                    (escape_string(form['login']), escape_string(password),
                     escape_string(form['email'])))
                conn.commit()
                flash("Zarejestrowano pomyślnie!", 'success')
                send_confirmation_email(form['email'])
                con.close()
                conn.close()
                gc.collect()
                return redirect(url_for('login', next=next_url,
                                        username=email))
            else:
                return render_template('register.html')
        except Exception as error:
            flash('Błąd: ' + str(error), 'danger')
            return redirect('/')
    else:
        flash("Jesteś już zalogowany!", 'warning')
        return redirect(next_url)
示例#53
0
def leaderboard2():
    # quizname = ['Doraemon', 'Shinchan', 'Chhota Bheem', 'Ninja Hattori' ]
    c, conn = connection()
    # m = {}
    c.execute(
        "select username, sum(score),sum(timing) from scoreboard group by username order by sum(score) desc, sum(timing) asc"
    )
    # quiz = c.execute("SELECT * from scoreboard where quizname = \'%s\' ORDER BY score DESC, timing ASC" %thwart(name))
    data = c.fetchall()
    # m[name]=data
    c.close()
    conn.close()
    if 'user' in session:
        return render_template('leaderboard2.html', data=data, len=len(data))
    return "YOU MUST LOGIN!"
示例#54
0
def download_file():
    c, conn = connection()

    c.execute("SELECT * FROM tbl_profiles")
    Details = [
        dict(id=row[0],
             name=row[1],
             id_number=row[2],
             phone_number=row[3],
             debt_amount=row[4]) for row in c.fetchall()
    ]
    c.close()
    return excel.make_response_from_array([[1, 2], [3, 4]],
                                          "csv",
                                          file_name="export_data")
示例#55
0
def leaderboard2():
    c, conn = connection()
    c.execute(
        "select username, sum(score),sum(timing) from scoreboard group by username order by sum(score) desc, sum(timing) asc"
    )
    data = c.fetchall()
    c.close()
    conn.close()
    if 'user' in session:
        return render_template(
            'leaderboard2.html',
            data=data,
            len=len(data),
            column=['Rank', 'Username', 'Total Score', 'Total Time'])
    return "YOU MUST LOGIN!"
def getLinks():
    c, conn = connection()
    html_file = open('bbc_rssfeed.html', 'w+')
    c.execute('SELECT link FROM rss_links')
    rows = c.fetchall()
    loopCount = 0
    rowCount = c.rowcount
    for row in rows:
        link_tag = '<a href="' + row[0] + '">' + row[0][26:] + '</a>'
        html_file.append(link_tag)
        loopCount = loopCount + 1
    conn.close()
    if loopCount == rowCount:
        return 1
    return 0
示例#57
0
def scouting_troop_create(name, scout_team_id, notify=True):
    con, conn = connection()
    sql = "INSERT INTO scouting_troop (name, scout_team_id) VALUES (%s, %s)"
    con.execute("SELECT name FROM scout_team WHERE id_scout_team = %s",
                escape_string(str(scout_team_id)))
    scout_team = con.fetchone()
    con.execute(sql, (escape_string(name), escape_string(str(scout_team_id))))
    conn.commit()
    if notify:
        flash("Stworzono \"{}\" w {}".format(name, scout_team['name']),
              'success')
    scouting_troop_id = con.lastrowid
    con.close()
    conn.close()
    return scouting_troop_id
示例#58
0
def user_auth_edit(username):
    error = ''
    try:
        username = username
        c, conn = connection()
        if request.method == "POST":
            permit = (request.values.get("user_auth")).encode('utf-8')

            #Be carefule!! Must use [] to quote username , otherwise it will
            #prompt a warning like: "not all arguments converted during string formatting"
            c.execute(
                "update login_user set auth_type='%s' where username='******'" %
                (permit, username))
            conn.commit()

            c.close()
            conn.close()
            gc.collect()
            flash(u'用户权限更新成功!')
            return redirect(url_for('user_list'))
        else:
            c, conn = connection()
            c.execute("select * from login_user where username = (%s)",
                      [username])
            auth_type_db = c.fetchone()[5]

            #Get number of logs/login_user/docs and display them with "bootstrap badge"
            num_logs = (sysadm_badges_number())[0]
            num_users = (sysadm_badges_number())[1]
            num_docs = (sysadm_badges_number())[2]

            return render_template("user-auth-edit.html", title=u'修改权限', auth_type_db=auth_type_db, \
   username=username, num_logs=num_logs, num_users=num_users, num_docs=num_docs, error=error)

    except Exception as e:
        return str(e)
示例#59
0
def fetchcourses():
    cursor, conn = connection()
    sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'moodle' AND TABLE_NAME = 'studentsdata'"
    cursor.execute(sql)
    conn.close()
    rows = [x for x in cursor]
    cols = [x[0] for x in cursor.description]
    ds = []
    for row in rows:
        d = {}
        for prop, val in zip(cols, row):
            if not val == "usn":
                d[prop] = val
                ds.append(d)
    return jsonify(ds)
示例#60
0
def delete_kegs():
    try:
        c, conn = connection()
        #keg_type = request.form["epc"]
        data = request.form["keg_ids"]

        idarray = data.split(',')

        for element in idarray:
            c.execute("DELETE FROM inventory WHERE keg_id=" + element)
        conn.commit()

        return jsonify({"epc": idarray})
    except Exception as e:
        return jsonify({"error": e})