简体   繁体   English

将python脚本重定向到另一个python脚本以验证登录凭据

[英]Redirect python script to another python script for validation of login credentials

I have a login python script in which i want to take the username and password and pass it to another python script which validates the username and password with the values in the database. 我有一个登录python脚本,我想在其中使用用户名和密码,并将其传递给另一个python脚本,该脚本使用数据库中的值验证用户名和密码。 If the user exists, it will create a cookie with the username value set in the cookie and redirect to the next page, otherwise, it will bring it back to the previous page. 如果用户存在,它将创建一个cookie,并在cookie中设置用户名值,然后重定向到下一页;否则,它将把它带回到上一页。

this is my index.py code: 这是我的index.py代码:

#!/usr/bin/python
import cgi;
import cgitb;
import sqlite3;
import os;
import Cookie;
import sys;



cgitb.enable()
form= cgi.FieldStorage()
username= None
userID = None
userPW= None

#Open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()





def createdb():
    ###Create table login
    conn.execute(""" CREATE TABLE login (userid INTEGER PRIMARY KEY ,
    username TEXT, passwrd TEXT)""")
    ##
    ###Create table excursion
    conn.execute(""" CREATE TABLE excursion (excurid INTEGER PRIMARY KEY,
    location TEXT, excurDate TEXT, excurTime TEXT, user INTEGER, FOREIGN KEY(user) REFERENCES login(userid))""")
    ##
    #Create table sighting
    conn.execute(""" CREATE TABLE sighting (sightid INTEGER PRIMARY KEY,
    species TEXT, observation TEXT, loginuser INTEGER, userexcursion INTEGER, FOREIGN KEY(loginuser, userexcursion) REFERENCES excursion (user, excurid))""")
    ##
    #Insert username and password in login table
    conn.execute("""INSERT INTO login (userid,username,passwrd) VALUES(NULL,'Diego','diego')""")
    conn.commit()

    #Insert dummy data in excursion table
    conn.execute("""INSERT INTO excursion (excurid,location,excurDate,excurTime,user) VALUES(NULL,'Macquarie','04/01/2012','6:00pm',1)""")
    conn.execute("""INSERT INTO excursion (excurid,location,excurDate,excurTime,user) VALUES(NULL,'Carlton','04/05/2012','7:00am',1)""")
    conn.commit()

    #Insert dummy data in sighting table
    conn.execute("""INSERT INTO sighting (sightid,species,observation,loginuser,userexcursion) VALUES(NULL,'Duck','long beak',1,1)""")
    conn.execute("""INSERT INTO sighting (sightid,species,observation,loginuser,userexcursion) VALUES(NULL,'Parrots','beautiful and colorful',1,2)""")
    conn.commit()
    conn.close()       



if not os.path.exists("manager.db"):
    createdb();

#define start of page
pagehead1= """
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
        <title> Home </title>
        <link rel='stylesheet' type='text/css' href='/index.css/'/>
    </head>

    <body>
"""

pagehead2="""

        <form method=POST action="http://localhost:8000/cgi-bin/validate.py">
            <div id="container">
                <div id="header">
                    <h1> Field Note Manager </h1>
                    <p class= "description"> Observe...Record...Save! </p>
                </div>

                <div id="wrapper">
                    <div id="content">
                        <p> Username: <input type="text" name="usernameLogin"/> </p>
                        <br/>
                        <p> Password: <input type="password" name="passwordLogin"/> </p>
                        <br/>
                        <p id="login"> <input type="submit" name="loginBtn" value="Login"/> </p>
                    </div>
                </div>

                <div id="footer">
                    <p> Copyright 42578647, 2012 </p>
                </div>
            </div>
    """

pagefoot= """ </form>
                  </body>
                  </html> """

print "Content_type: text/html\n\n"
print pagehead1
print pagehead2
print pagefoot

and this is my code for the validation of the username with the database: 这是我通过数据库验证用户名的代码:

#! usr/local/bin/python
import cgi;
import cgitb;
import Cookie;
import os;
import sqlite3;

#open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()

username= None
form= cgi.FieldStorage()

UserPW= [form.getvalue('usernameLogin'), form.getvalue('passwordLogin')]
isValidate = validate(UserPW);

if isValidate == 1:
    print "Content_type: text/html\n\n"
    print """
    <html>
        <head> Redirecting </head>
        <body>
            <form method= POST action="http://localhost:8000/cgi-bin/page1.py">
            <p> Validated! <input type="submit" value="Enter"/> </p>
            </form>
        </body>
    </html> """
elif isValidate == 0:
    print "Content_type: text/html\n\n"
    print """
    <html>
        <head> Redirecting </head>
        <body>
            <form method=POST action= "http://localhost:8000/cgi-bin/index.py">
                <p> Username or Password incorrect! <input type="submit" value="Go back"/> </p>
            </form>
        </body>
    </html>
    """



def validate(UserPW):
    sql= "SELECT * FROM login"
    userPWDatabase=cur.execute(sql)
    cur.fetchall()
    for record in userPWDatabase:
        if record == UserPW:
            #Create cookie
            C= Cookie.SimpleCookie()
            #take the value of the index.py form variable username
            username= form.getvalue('usernameLogin')
            #set the cookie with the usernameLogin key
            C['usernameLogin']= username
            print C
            return 1
        else:
            return 0              

I don't know where is the problem 我不知道问题出在哪里

Could you please give more details than "I don't know where is the problem": what exactly happens, what log messages you get if there are some. 除了“我不知道问题出在哪里”之外,您能否提供更多详细信息:到底发生了什么,如果出现一些日志消息。

Have you tried to move the "validate" function definition before it's called? 您是否曾尝试在调用“验证”函数定义之前将其移走? I think this can be part of your problem. 我认为这可能是您的问题的一部分。


Update: after some investigations and few fixes, I got it working: 更新:经过一些调查和少量修复后,我开始运行了:

  1. As said previously, the "validate" function definition should be set before it's called 如前所述,“ validate”函数定义应在调用之前进行设置
  2. Your sql query is not correct, as "SELECT * FROM login" will return 3 fields ( id, username and passwrd), so you should change it to "SELECT username,passwrd FROM login" 您的sql查询不正确,因为“ SELECT * FROM login”将返回3个字段(id,username和passwrd),因此您应将其更改为“ SELECT username,passwrd FROM login”
  3. The record returned by sqlite is a tuple, and you're trying to compate it to a list, so there's a TYPE mismatch. sqlite返回的记录是一个元组,并且您正在尝试将其填充为列表,因此存在TYPE不匹配。 One solution if to change to : "if list(record) == UserPW:" 一种解决方案,如果更改为:“ if list(record)== UserPW:”

Also, under ubuntu looking at /var/log/apache2/error.log helps a lot. 另外,在ubuntu下查看/var/log/apache2/error.log会有很大帮助。

Which finally led to: 最终导致:

#!/usr/bin/env python

import cgi;
import cgitb;
import Cookie;
import os;
import sqlite3;

#open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()

username= None
form= cgi.FieldStorage()


def validate(UserPW):
      sql= "SELECT username,passwrd FROM login;"
      cur.execute(sql)
      userPWDatabase=cur.fetchall()
      for record in userPWDatabase:
          if list(record) == UserPW:
              #Create cookie
              C= Cookie.SimpleCookie()
              #take the value of the index.py form variable username
              username= form.getvalue('usernameLogin')
              #set the cookie with the usernameLogin key
              C['usernameLogin']= username
              print C
              return 1
          else:
              return 0              



UserPW= [form.getvalue('usernameLogin'), form.getvalue('passwordLogin')]
isValidate = validate(UserPW);

if isValidate == 1:
      print "Content-type: text/html\n\n"
      print """
      <html>
          <head> Redirecting </head>
          <body>
              <form method= POST action="http://localhost:8000/cgi-bin/page1.py">
              <p> Validated! <input type="submit" value="Enter"/> </p>
              </form>
          </body>
      </html> """
elif isValidate == 0:
      print "Content-type: text/html\n\n"
      print """
      <html>
          <head> Redirecting </head>
          <body>
              <form method=POST action= "http://localhost:8000/cgi-bin/index.py">
                  <p> Username or Password incorrect! <input type="submit" value="Go back"/> </p>
              </form>
          </body>
      </html>
      """

I changed the code validate.py to this: 我将代码validate.py更改为:

  #! usr/local/bin/python
import cgi;
import cgitb;
import Cookie;
import os;
import sqlite3;

cgitb.enable()
username= None
form= cgi.FieldStorage()

#open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()

pagehead= """
    <html>
        <head> Redirecting </head>
        <body>

            """
pagefoot="""<form method= POST action="http://localhost:8000/cgi-bin/page1.py">
            <p> Validated! <input type="submit" value="Enter"/> </p>
            </form>
        </body>
    </html> """
errorpagefoot= """
<form action="http://localhost:8000/cgi-bin/index.py">
<p> Error! <input type="submit" value="Go Back"/> </p>
</form>
</body>
</html>"""


print "Content_type: text/html\n\n"
print pagehead
userName= form.getvalue('usernameLogin')
userPW= form.getvalue('passwordLogin')
userPWDatabase = conn.execute("SELECT username,passwrd FROM login WHERE username=? and passwrd=?",[userName,userPW])
cur.fetchone()
for result in userPWDatabase:
    userDb= result[0]
    pwDb= result[1]
    if userDb == userName and pwDb == userPW:
        #Create Cookie
        C= Cookie.SimpleCookie()
        #take the value of usernameLogin into the variable username
        username= form.getvalue('usernameLogin')
        #Set-Cookie header with the usernameLogin key
        C['usernameLogin'] = username
        print C
        print pagefoot    
    elif userDb != userName and pwDb != userPW:
        print errorpagefoot

it's working now but it doesnt redirect to the previous page anymore, incase of incorrect username or password 现在可以正常使用,但是如果用户名或密码不正确,它也不会重定向到上一页

Ok, after reading your new code it seems you still have several bugs, but the main error I think is the way you try to check the login/password: first you select it from the database byt filtering on the username and password, which can only return 1 or 0 result as the login is a primary in your db, and then you try to loop on the results and check if the username and password are both correct, or both incorrect, which consequently does not cover the case when username is correct but not the password ( and inverse ). 好的,在阅读完新代码之后,看来您仍然有几个错误,但是我认为主要的错误是您尝试检查登录名/密码的方式:首先,您通过筛选用户名和密码从数据库中选择登录名/密码,仅返回1或0的结果,因为登录名是您数据库中的主要用户,然后您尝试循环搜索结果,并检查用户名和密码是否正确或正确,因此不涉及用户名为更正密码而不是密码(和取反)。 So I suggest you change the last part of your code for this: 因此,我建议您为此更改代码的最后一部分:

print "Content-type: text/html\n\n"
print pagehead
userName= form.getvalue('usernameLogin')
userPW= form.getvalue('passwordLogin')
cur.execute("SELECT username,passwrd FROM login WHERE username=?",[userName])
userPWDatabase = cur.fetchone()
if userPWDatabase is not None:
        userDb= userPWDatabase[0]
        pwDb= userPWDatabase[1]
        #Create Cookie
        C= Cookie.SimpleCookie()
        #take the value of usernameLogin into the variable username
        username= form.getvalue('usernameLogin')
        #Set-Cookie header with the usernameLogin key
        C['usernameLogin'] = username
        print C
        print pagefoot    
else:
        print errorpagefoot

Note that you could also keep your SQL query with filter on username and password, but then you don't need to check anything else: if there's no result, one of the two field is incorrect, and there's one it's necessarily good. 请注意,您还可以保留对用户名和密码进行过滤的SQL查询,但是然后您无需检查其他任何内容:如果没有结果,则两个字段之一不正确,有一个字段必定是好的。

In addition, I don't know what's your aim ( either to learn cgi-bin/python or setup a real application ), but you might be interested to have a look at Django ( www.djangoproject.com ) 另外,我不知道您的目标是什么(学习cgi-bin / python或设置真实的应用程序),但是您可能有兴趣看看Django( www.djangoproject.com

i just read that the Set-Cookie header stuff is suppose to be before the line: 我刚刚读到Set-Cookie标头的内容应该在该行之前:

print "Content_type: text/html\n\n"

so, i fixed my code again and it's working fine now. 因此,我再次修复了代码,现在可以正常工作。 it goes back to previous script in case of wrong username / password and it proceeds to next script after validation Here is the final code: 如果用户名/密码错误,它将返回上一个脚本,并在验证后进入下一个脚本。这是最终代码:

#! usr/local/bin/python
import cgi;
import cgitb;
import Cookie;
import os;
import sqlite3;

cgitb.enable()
username= None
form= cgi.FieldStorage()

#open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()

pagehead= """
    <html>
        <head> Redirecting </head>
        <body>

            """
pagefoot="""<form method= POST action="http://localhost:8000/cgi-bin/page1.py">
            <p> Validated! <input type="submit" value="Enter"/> </p>
            </form>
        </body>
    </html> """
errorpagefoot= """
<form action="http://localhost:8000/cgi-bin/index.py">
<p> Error! <input type="submit" value="Go Back"/> </p>
</form>
</body>
</html>"""


userName= form.getvalue('usernameLogin')
userPW= form.getvalue('passwordLogin')
userPWDatabase = conn.execute("SELECT username,passwrd FROM login WHERE username=? and passwrd=?",[userName,userPW])
cur.fetchone()
for result in userPWDatabase:
    userDb= result[0]
    pwDb= result[1]
    if userDb == userName and pwDb == userPW:
        #Create Cookie
        C= Cookie.SimpleCookie()
        #take the value of usernameLogin into the variable username
        username= form.getvalue('usernameLogin')
        #Set-Cookie header with the usernameLogin key
        C['usernameLogin'] = username
        print C
    elif userDb != userName and pwDb != userPW:
        print errorpagefoot

print "Content_type: text/html\n\n"
print pagehead
if username:
    print pagefoot
else:
    print errorpagefoot

@Alexis @亚历克西斯

Thanks for your time and help Alexis :) 感谢您的时间和帮助亚历克西斯:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM