auth + creating identities
This commit is contained in:
58
login.go
Normal file
58
login.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"libshared"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type LoginRequest struct {
|
||||
AccountID int64 `json:"account_id"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
//ctx := r.Context()
|
||||
|
||||
var req LoginRequest
|
||||
var ok bool
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var storedHash string
|
||||
|
||||
err = libshared.Pool.QueryRow(
|
||||
context.Background(),
|
||||
`SELECT password_hash
|
||||
FROM identities
|
||||
WHERE accountid=$1 AND provider_user_id=$2`,
|
||||
req.AccountID,
|
||||
req.Username,
|
||||
).Scan(&storedHash)
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, "invalid credentials", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
ok = verifyPassword(req.Password, storedHash)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
http.Error(w, "authentication error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if !ok {
|
||||
http.Error(w, "invalid credentials", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("login successful"))
|
||||
}
|
||||
Reference in New Issue
Block a user