signins
This commit is contained in:
@@ -1,11 +1,12 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
// "strings"
|
||||
"os"
|
||||
"strings"
|
||||
"strconv"
|
||||
|
||||
"hyperia/db"
|
||||
|
||||
@@ -29,28 +30,57 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
var creds loginRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&creds); err != nil {
|
||||
http.Error(w, "Invalid JSON", http.StatusBadRequest)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "Unable to parse form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
creds.Email = email
|
||||
creds.Password = password
|
||||
|
||||
user, err := getUserByCredentials(creds)
|
||||
if err != nil {
|
||||
if err != nil || user == nil {
|
||||
http.Error(w, "Unauthorized: "+ err.Error(), http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
http.Error(w, "Not implemented", http.StatusMethodNotAllowed)
|
||||
json.NewEncoder(w).Encode(user)
|
||||
keyInt, err := strconv.Atoi(user["key"].(string))
|
||||
if err != nil {
|
||||
// This means the string couldn't be parsed as an int — handle it
|
||||
log.Println("user['key'] is not a valid int:", err)
|
||||
http.Error(w, "internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
jwtToken, err := GenerateJWT(keyInt)
|
||||
if err != nil {
|
||||
log.Println("JWT generation error:", err)
|
||||
http.Error(w, "Failed to generate auth token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
cookie := &http.Cookie{
|
||||
Name: "auth_token",
|
||||
Value: jwtToken,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Domain: "." + os.Getenv("BASE_URL"), // or ".localhost" — this allows subdomains
|
||||
Secure: true, // default to true (production)
|
||||
MaxAge: 2 * 60 * 60,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
}
|
||||
|
||||
http.SetCookie(w, cookie)
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func getUserByCredentials(loginCreds loginRequest) (map[string]interface{}, error) {
|
||||
|
||||
// email := strings.TrimSpace(strings.ToLower(loginCreds.Email))
|
||||
email := strings.TrimSpace(strings.ToLower(loginCreds.Email))
|
||||
|
||||
user, err := db.Get.User("1")
|
||||
// err := DB.QueryRow("SELECT id, name, password FROM users WHERE LOWER(name) = LOWER($1)", name).Scan(&id, &dbName, &dbHash)
|
||||
user, err := db.Get.UserByEmail(email)
|
||||
if err != nil {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user