up
This commit is contained in:
316
internal/auth/auth.go
Normal file
316
internal/auth/auth.go
Normal file
@@ -0,0 +1,316 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// ── Models ────────────────────────────────────────────────────────────────────
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type contextKey string
|
||||
|
||||
const userKey contextKey = "user"
|
||||
|
||||
// ── Store ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
type Store struct{ db *sql.DB }
|
||||
|
||||
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
|
||||
|
||||
func (s *Store) GetByEmail(email string) (*User, string, error) {
|
||||
var u User
|
||||
var hash string
|
||||
err := s.db.QueryRow(
|
||||
`SELECT id, email, name, password_hash, created_at FROM users WHERE email=?`, email,
|
||||
).Scan(&u.ID, &u.Email, &u.Name, &hash, &u.CreatedAt)
|
||||
return &u, hash, err
|
||||
}
|
||||
|
||||
func (s *Store) GetByID(id string) (*User, error) {
|
||||
var u User
|
||||
err := s.db.QueryRow(
|
||||
`SELECT id, email, name, created_at FROM users WHERE id=?`, id,
|
||||
).Scan(&u.ID, &u.Email, &u.Name, &u.CreatedAt)
|
||||
return &u, err
|
||||
}
|
||||
|
||||
func (s *Store) List() ([]User, error) {
|
||||
rows, err := s.db.Query(`SELECT id, email, name, created_at FROM users ORDER BY created_at`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var users []User
|
||||
for rows.Next() {
|
||||
var u User
|
||||
if err := rows.Scan(&u.ID, &u.Email, &u.Name, &u.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
users = append(users, u)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (s *Store) Create(email, name, password string) (*User, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u := &User{ID: uuid.NewString(), Email: email, Name: name}
|
||||
_, err = s.db.Exec(
|
||||
`INSERT INTO users (id, email, name, password_hash) VALUES (?,?,?,?)`,
|
||||
u.ID, u.Email, u.Name, string(hash),
|
||||
)
|
||||
return u, err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateProfile(id, email, name string) error {
|
||||
_, err := s.db.Exec(`UPDATE users SET email=?, name=? WHERE id=?`, email, name, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdatePassword(id, newPassword string) error {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.Exec(`UPDATE users SET password_hash=? WHERE id=?`, string(hash), id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Delete(id string) error {
|
||||
_, err := s.db.Exec(`DELETE FROM users WHERE id=?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Count() int {
|
||||
var n int
|
||||
s.db.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
|
||||
return n
|
||||
}
|
||||
|
||||
func (s *Store) CheckPassword(id, password string) bool {
|
||||
var hash string
|
||||
s.db.QueryRow(`SELECT password_hash FROM users WHERE id=?`, id).Scan(&hash)
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
||||
}
|
||||
|
||||
// Sessions en mémoire
|
||||
var sessions = map[string]string{}
|
||||
|
||||
func (s *Store) CreateSession(userID string) string {
|
||||
token := uuid.NewString()
|
||||
sessions[token] = userID
|
||||
return token
|
||||
}
|
||||
|
||||
func (s *Store) GetUserFromToken(token string) (*User, error) {
|
||||
id, ok := sessions[token]
|
||||
if !ok {
|
||||
return nil, sql.ErrNoRows
|
||||
}
|
||||
return s.GetByID(id)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteSession(token string) {
|
||||
delete(sessions, token)
|
||||
}
|
||||
|
||||
// ── Handler ───────────────────────────────────────────────────────────────────
|
||||
|
||||
type Handler struct{ store *Store }
|
||||
|
||||
func NewHandler(store *Store) *Handler { return &Handler{store: store} }
|
||||
|
||||
func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user, hash, err := h.store.GetByEmail(body.Email)
|
||||
if err != nil || bcrypt.CompareHashAndPassword([]byte(hash), []byte(body.Password)) != nil {
|
||||
http.Error(w, "identifiants incorrects", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
token := h.store.CreateSession(user.ID)
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "session", Value: token, Path: "/",
|
||||
HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
||||
Expires: time.Now().Add(30 * 24 * time.Hour),
|
||||
})
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"user": user, "token": token})
|
||||
}
|
||||
|
||||
func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
c, err := r.Cookie("session")
|
||||
if err == nil {
|
||||
h.store.DeleteSession(c.Value)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "session", MaxAge: -1, Path: "/"})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
user := r.Context().Value(userKey).(*User)
|
||||
respond(w, user)
|
||||
}
|
||||
|
||||
// Register — public si aucun user, sinon auth requise
|
||||
func (h *Handler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body.Email == "" || body.Name == "" || body.Password == "" {
|
||||
http.Error(w, "email, nom et mot de passe requis", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(body.Password) < 6 {
|
||||
http.Error(w, "mot de passe trop court (6 caractères minimum)", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user, err := h.store.Create(body.Email, body.Name, body.Password)
|
||||
if err != nil {
|
||||
http.Error(w, "email déjà utilisé", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
token := h.store.CreateSession(user.ID)
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "session", Value: token, Path: "/",
|
||||
HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
||||
Expires: time.Now().Add(30 * 24 * time.Hour),
|
||||
})
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]any{"user": user, "token": token})
|
||||
}
|
||||
|
||||
// UpdateProfile — modifier nom + email
|
||||
func (h *Handler) UpdateProfile(w http.ResponseWriter, r *http.Request) {
|
||||
user := r.Context().Value(userKey).(*User)
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body.Email == "" || body.Name == "" {
|
||||
http.Error(w, "email et nom requis", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := h.store.UpdateProfile(user.ID, body.Email, body.Name); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
user.Email = body.Email
|
||||
user.Name = body.Name
|
||||
respond(w, user)
|
||||
}
|
||||
|
||||
// UpdatePassword — changer son mot de passe
|
||||
func (h *Handler) UpdatePassword(w http.ResponseWriter, r *http.Request) {
|
||||
user := r.Context().Value(userKey).(*User)
|
||||
var body struct {
|
||||
Current string `json:"current_password"`
|
||||
New string `json:"new_password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !h.store.CheckPassword(user.ID, body.Current) {
|
||||
http.Error(w, "mot de passe actuel incorrect", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if len(body.New) < 6 {
|
||||
http.Error(w, "nouveau mot de passe trop court (6 caractères minimum)", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := h.store.UpdatePassword(user.ID, body.New); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ListUsers — liste tous les utilisateurs (admin)
|
||||
func (h *Handler) ListUsers(w http.ResponseWriter, r *http.Request) {
|
||||
users, err := h.store.List()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if users == nil {
|
||||
users = []User{}
|
||||
}
|
||||
respond(w, users)
|
||||
}
|
||||
|
||||
// DeleteUser — supprimer un utilisateur (ne peut pas se supprimer soi-même)
|
||||
func (h *Handler) DeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
me := r.Context().Value(userKey).(*User)
|
||||
id := mux.Vars(r)["id"]
|
||||
if id == me.ID {
|
||||
http.Error(w, "impossible de supprimer son propre compte", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := h.store.Delete(id); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ── Middleware ────────────────────────────────────────────────────────────────
|
||||
|
||||
func Middleware(store *Store) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token := ""
|
||||
if c, err := r.Cookie("session"); err == nil {
|
||||
token = c.Value
|
||||
}
|
||||
if token == "" {
|
||||
token = r.Header.Get("Authorization")
|
||||
}
|
||||
user, err := store.GetUserFromToken(token)
|
||||
if err != nil {
|
||||
http.Error(w, "non autorisé", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userKey, user)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func respond(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
Reference in New Issue
Block a user