英文:
Go checking login values before login
问题
我有一个登录表单,当我点击发送时,页面会重定向到/create
。在那里,我会在一个GO函数中检查我的登录值是否正确,以便给予下一页的访问权限,但是我的函数有问题。
loginCheck:
func loginCheck(w http.ResponseWriter, r* http.Request){
r.ParseForm()
//调用DB函数
db:= SetupDB()
name, password := r.FormValue("user"), r.FormValue("password")
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
PanicIf(err)
rows, err := db.Query("SELECT name, password from users where name = $1 and password = $2" ,name, hashedPassword)
PanicIf(err)
defer rows.Close()
for rows.Next() {
err := rows.Scan(&name, &hashedPassword)
PanicIf(err)
fmt.Println(name, hashedPassword)
}
db.Close()
}
我试图在rows.Next()
中打印值,以查看是否从数据库中读取了值,但是它是空的。
英文:
I got a login form, when I click on send, I redirect the page to a /create
. There I check in a GO function if the values of my login are the correct to give access to the next page, but I have a problem with my function.
loginCheck:
func loginCheck(w http.ResponseWriter, r* http.Request){
r.ParseForm()
//Call the DB function
db:= SetupDB()
name, password := r.FormValue("user"), r.FormValue("password")
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
PanicIf(err)
rows, err := db.Query("SELECT name, password from users where name = $1 and password = $2" ,name, hashedPassword)
PanicIf(err)
defer rows.Close()
for rows.Next() {
err := rows.Scan(&name, &hashedPassword)
PanicIf(err)
fmt.Println(name, hashedPassword)
}
db.Close()
}
Im trying to print the values inside the rows.Next() to see if read the values from the database but it's empty.
答案1
得分: 5
为了补充seong的评论,你可以考虑参考goserver中的这个例子:
func CheckPassword(username, password string) bool {
if len(username) == 0 || len(password) == 0 {
return false
}
var hashPw []byte
err := DB.QueryRow("SELECT password FROM users WHERE username=?", username).Scan(&hashPw)
if err != nil {
log.Println("CheckPassword", err.Error())
return false
}
if len(hashPw) == 0 {
return false
}
err = bcrypt.CompareHashAndPassword(hashPw, []byte(password))
if err == nil {
return true
}
return false
}
查询只使用了username
。
英文:
To add to seong's comment, you can consider this example in goserver:
func CheckPassword(username, password string) bool {
if len(username) == 0 || len(password) == 0 {
return false
}
var hashPw []byte
err := DB.QueryRow("SELECT password FROM users WHERE username=?", username).Scan(&hashPw)
if err != nil {
log.Println("CheckPassword", err.Error())
return false
}
if len(hashPw) == 0 {
return false
}
err = bcrypt.CompareHashAndPassword(hashPw, []byte(password))
if err == nil {
return true
}
return false
}
The query is done using only username
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论