login.go (1032B)
1 package main 2 3 import ( 4 "crypto/sha512" 5 "encoding/json" 6 "net/http" 7 "uuid" 8 9 "github.com/gboncoffee/siga/auth/repository" 10 ) 11 12 type LoginRequest struct { 13 Username string 14 Password string 15 } 16 17 type LoginResponse struct { 18 Token uuid.UUID 19 } 20 21 func login(w http.ResponseWriter, r *http.Request) { 22 var req LoginRequest 23 if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 24 http.Error(w, "invalid JSON", http.StatusBadRequest) 25 return 26 } 27 28 c, err := repository.GetByUsername(req.Username) 29 if err != nil { 30 http.Error(w, "invalid username or password", http.StatusUnauthorized) 31 return 32 } 33 34 if c.Password != sha512.Sum512([]byte(req.Password)) { 35 http.Error(w, "invalid username or password", http.StatusUnauthorized) 36 return 37 } 38 39 token := uuid.New() 40 if err := repository.NewSession(token, c.Username); err != nil { 41 http.Error(w, 42 "internal server error", 43 http.StatusInternalServerError, 44 ) 45 return 46 } 47 48 w.Header().Set("Content-Type", "application/json") 49 json.NewEncoder(w).Encode(LoginResponse{Token: token}) 50 }