create password auth skeleton
This commit is contained in:
55
api/user.go
55
api/user.go
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/render"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func UserCtx(next http.Handler) http.Handler {
|
||||
@@ -67,10 +68,17 @@ func NewUser(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
newUserName := r.FormValue("name")
|
||||
password := r.FormValue("password")
|
||||
if newUserName == "" || password == "" {
|
||||
http.Error(w, "Username and password cannot be empty", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword, err := hashPassword(password)
|
||||
newUser := User{
|
||||
ID: newUserID(),
|
||||
Name: newUserName,
|
||||
ID: newUserID(),
|
||||
Name: newUserName,
|
||||
Password: hashedPassword,
|
||||
}
|
||||
|
||||
err = dbAddUser(&newUser)
|
||||
@@ -82,15 +90,54 @@ func NewUser(w http.ResponseWriter, r *http.Request) {
|
||||
render.Render(w, r, NewUserPayloadResponse(&newUser))
|
||||
}
|
||||
|
||||
func Login(w http.ResponseWriter, r *http.Request) {
|
||||
err := r.ParseMultipartForm(64 << 10)
|
||||
if err != nil {
|
||||
http.Error(w, "Unable to parse form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
username := r.FormValue("name")
|
||||
password := r.FormValue("password")
|
||||
if username == "" || password == "" {
|
||||
http.Error(w, "Username and password cannot be empty", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := dbGetUserByName(username)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid username or password", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
err = validatePassword(user.Password, password)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid username or password", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
w.Write([]byte("Login successful"))
|
||||
}
|
||||
|
||||
func (u *UserPayload) Render(w http.ResponseWriter, r *http.Request) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func hashPassword(password string) (string, error) {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
return string(hashedPassword), err
|
||||
}
|
||||
|
||||
func validatePassword(hashedPassword, password string) error {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
|
||||
}
|
||||
|
||||
type userKey struct{}
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Password string `json:"-"`
|
||||
}
|
||||
|
||||
type UserPayload struct {
|
||||
|
Reference in New Issue
Block a user