63 lines
2.4 KiB
Go
63 lines
2.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"log"
|
|
"net/http"
|
|
"threadr/models"
|
|
"github.com/gorilla/sessions"
|
|
)
|
|
|
|
func LoginHandler(app *App) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
session := r.Context().Value("session").(*sessions.Session)
|
|
if r.Method == http.MethodPost {
|
|
username := r.FormValue("username")
|
|
password := r.FormValue("password")
|
|
user, err := models.GetUserByUsername(app.DB, username)
|
|
if err != nil && err != sql.ErrNoRows {
|
|
log.Printf("Error fetching user in LoginHandler: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if user == nil || !models.CheckPassword(password, user.AuthenticationSalt, user.AuthenticationAlgorithm, user.AuthenticationString) {
|
|
http.Redirect(w, r, app.Config.ThreadrDir+"/login/?error=invalid", http.StatusFound)
|
|
return
|
|
}
|
|
session.Values["user_id"] = user.ID
|
|
session.Values["user_ip"] = r.RemoteAddr
|
|
session.Values["user_agent"] = r.UserAgent()
|
|
if err := session.Save(r, w); err != nil {
|
|
log.Printf("Error saving session: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
http.Redirect(w, r, app.Config.ThreadrDir+"/userhome/", http.StatusFound)
|
|
return
|
|
}
|
|
|
|
data := struct {
|
|
PageData
|
|
Error string
|
|
}{
|
|
PageData: PageData{
|
|
Title: "ThreadR - Login",
|
|
Navbar: "login",
|
|
LoggedIn: false,
|
|
BasePath: app.Config.ThreadrDir,
|
|
StaticPath: app.Config.ThreadrDir + "/static",
|
|
CurrentURL: r.URL.Path,
|
|
},
|
|
Error: "",
|
|
}
|
|
if r.URL.Query().Get("error") == "invalid" {
|
|
data.Error = "Invalid username or password"
|
|
}
|
|
|
|
if err := app.Tmpl.ExecuteTemplate(w, "login", data); err != nil {
|
|
log.Printf("Error executing template in LoginHandler: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
} |