pye/auth.go

62 lines
1.7 KiB
Go
Raw Normal View History

2024-10-11 11:38:08 +03:00
package main
import (
2024-10-11 23:57:57 +03:00
"log/slog"
2024-10-11 11:38:08 +03:00
"net/http"
"net/mail"
"strings"
)
func ValidEmail(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
}
func ValidPass(pass string) bool {
return len(pass) >= 8 // TODO: Obviously, we *might* want something more sophisticated here
}
2024-10-11 23:57:57 +03:00
func EmailTaken(email string) bool {
// TODO: Implement properly
return EmailExists(email)
2024-10-11 11:38:08 +03:00
}
func Register(w http.ResponseWriter, r *http.Request) {
email, password, ok := r.BasicAuth()
if !ok {
email = strings.TrimSpace(email)
password = strings.TrimSpace(password)
2024-10-11 23:57:57 +03:00
if !(ValidEmail(email) || ValidPass(password) || EmailTaken(email)) {
2024-10-11 11:38:08 +03:00
// TODO: Provide descriptive error and check if 400 is best code?
http.Error(w, "Invalid auth credentials", http.StatusBadRequest)
2024-10-11 23:57:57 +03:00
return
2024-10-11 11:38:08 +03:00
}
2024-10-11 23:57:57 +03:00
user, err := NewUser(email, password)
if err != nil {
slog.Error("Error creating a new user", "error", err)
}
AddUser(user)
2024-10-11 11:38:08 +03:00
}
// No email and password was provided
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "This API requires authorization", http.StatusUnauthorized)
}
2024-10-11 23:57:57 +03:00
func Login(w http.ResponseWriter, r *http.Request) {
email, password, ok := r.BasicAuth()
if !ok {
email = strings.TrimSpace(email)
password = strings.TrimSpace(password)
user, ok := ByEmail(email)
if !ok || !user.PasswordFits(password) {
http.Error(w, "You did something wrong", http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusOK)
}
// No email and password was provided
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "This API requires authorization", http.StatusUnauthorized)
}