forked from mtusi2026/mtusi2026lab2
Implement lab2 messenger API with PostgreSQL Redis and Docker
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
var usernameRegexp = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserHandler struct {
|
||||
store *storage.AuthStore
|
||||
}
|
||||
|
||||
func NewUserHandler(store *storage.AuthStore) *UserHandler {
|
||||
return &UserHandler{store: store}
|
||||
}
|
||||
|
||||
type createUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
1,
|
||||
64*1024,
|
||||
4,
|
||||
32,
|
||||
)
|
||||
|
||||
return "argon2id$" +
|
||||
base64.RawStdEncoding.EncodeToString(salt) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(hash), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 3 || parts[0] != "argon2id" {
|
||||
return false
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
|
||||
if err != nil || len(salt) != 16 {
|
||||
return false
|
||||
}
|
||||
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[2])
|
||||
if err != nil || len(expected) != 32 {
|
||||
return false
|
||||
}
|
||||
|
||||
actual := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
1,
|
||||
64*1024,
|
||||
4,
|
||||
32,
|
||||
)
|
||||
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var req createUserRequest
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if !usernameRegexp.MatchString(req.Username) {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
|
||||
req.DisplayName = strings.TrimSpace(req.DisplayName)
|
||||
nameLength := utf8.RuneCountInString(req.DisplayName)
|
||||
|
||||
if nameLength < 1 || nameLength > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid display_name")
|
||||
return
|
||||
}
|
||||
|
||||
passwordLength := utf8.RuneCountInString(req.Password)
|
||||
if passwordLength < 12 || passwordLength > 128 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request",
|
||||
"password must contain 12 to 128 characters")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := HashPassword(req.Password)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusInternalServerError,
|
||||
"internal_error", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err = h.store.CreateUser(r.Context(), user, passwordHash)
|
||||
if errors.Is(err, storage.ErrUsernameTaken) {
|
||||
writeError(w, r, http.StatusConflict,
|
||||
"conflict", "username already exists")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
Reference in New Issue
Block a user