righty_dev
righty_dev

Reputation: 27

authentication on golang/MySQL doesn't work

I wanted to create a registration/authorization on the site, registration is already working, but the authentication code for some reason is not. I expect to go to the home page if the data entered is correct(and the message is displayed in the opposite case), but it does not go. Maybe I'm doing the wrong thing in general, maybe the problem is in the code. Here is the code itself:

func log(w http.ResponseWriter, r *http.Request) {
FormEmail := r.FormValue("email")
FormPassword := r.FormValue("password")
var email string
var password string
// подключение
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:8889)/service")
if err != nil {
    panic(err)
}

defer db.Close()

// авторизация
res, err := db.Query(fmt.Sprintf("SELECT * FROM `users` WHERE `email` = '%s'", email))
result, error := db.Query(fmt.Sprintf("SELECT * FROM `users` WHERE `password` = '%s'", password))
if err != nil || error != nil {
    panic(err)
}

posts = []User{}
for res.Next() {
    var post User
    err = res.Scan(&post.Id, &post.Name, &post.Surname, &post.Email, &post.Number, &post.Password)
    if err != nil {
        panic(err)
    }
    if post.Email != FormEmail {
        fmt.Fprintf(w, "incorrect mail")
    }
}
for result.Next() {
    var post User
    error = res.Scan(&post.Id, &post.Name, &post.Surname, &post.Email, &post.Number, &post.Password)
    if error != nil {
        panic(err)
    }
    if post.Password != FormPassword {
        fmt.Fprintf(w, "incorrect password")
    }
}
http.Redirect(w, r, "/", http.StatusSeeOther)

} html:

    <form action="/log" method="post">
  <input type="email" name="email">
  <input type="password" name="password">
  <button>Login</button>
</form>

The idea is as follows: a person enters an email address and password into the form, and you need to check the data in the database. The user is created on top of the structure to which you assign data from the table field. formemail and formpassword are values from form fields, while email and password are initially empty variables of the with string type. No errors are displayed, the database is connected correctly. I think I'm doing something wrong, I'll be grateful for every hint. I apologize if the question is stupid, I'm just learning

Upvotes: 0

Views: 922

Answers (1)

righty_dev
righty_dev

Reputation: 27

I just solved this problem like this:

func log(w http.ResponseWriter, r *http.Request) {
    FormEmail := r.FormValue("email")
    FormPassword := r.FormValue("password")
    // connection
    db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:8889)/service")
    if err != nil {
        panic(err)
    }

    defer db.Close()

    // check if there is a user with the specified email + password
    res, err := db.Query(fmt.Sprintf("SELECT * FROM `users` WHERE `email` = '%s' and password = '%s'", FormEmail, FormPassword))
    if err != nil {
        fmt.Printf("%w", err)
        JSONError(500, "DB100 error code example", "DB error", w)
        return
    }
    
    // we check whether there are records in the database.
    if !res.Next() {
        JSONError(413, "trololo", "user not found", w)
        return
    }
    
    http.Redirect(w, r, "/", http.StatusSeeOther)
}


func JSONError(httpcode int, code, msg string, w http.ResponseWriter) {
    type Error struct {
        Code      *string `json:"code,omitempty"`
        Message   *string `json:"message,omitempty"`
    }
    
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.WriteHeader(httpcode)
    json.NewEncoder(w).Encode(
        Error{
            Code:      &code,
            Message:   &msg,
        },
    )
}

please don't repeat my mistakes

Upvotes: 1

Related Questions