|
| 1 | +// Copyright (c) 2025 SDSLabs |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package api |
| 5 | + |
| 6 | +import ( |
| 7 | + "encoding/json" |
| 8 | + "log" |
| 9 | + "net/http" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "github.com/sdslabs/nymeria/internal/database" |
| 13 | +) |
| 14 | + |
| 15 | +// HandleGetRegistrationFlow handles the GET request for the registration flow. |
| 16 | +func HandleGetRegistrationFlow(w http.ResponseWriter, r *http.Request) { |
| 17 | + if r.Method != http.MethodGet { |
| 18 | + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) |
| 19 | + return |
| 20 | + } |
| 21 | + |
| 22 | + w.Write([]byte("not implemented")) |
| 23 | +} |
| 24 | + |
| 25 | +// HandlePostRegistrationFlow handles the POST request for the registration flow. |
| 26 | +func HandlePostRegistrationFlow(w http.ResponseWriter, r *http.Request) { |
| 27 | + if r.Method != http.MethodPost { |
| 28 | + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + var req RegistrationRequest |
| 33 | + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 34 | + http.Error(w, "Invalid JSON", http.StatusBadRequest) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + if req.Username == "" { |
| 39 | + http.Error(w, "Username is required", http.StatusBadRequest) |
| 40 | + return |
| 41 | + } |
| 42 | + if req.Password == "" { |
| 43 | + http.Error(w, "Password is required", http.StatusBadRequest) |
| 44 | + return |
| 45 | + } |
| 46 | + if req.Email == "" { |
| 47 | + http.Error(w, "Email is required", http.StatusBadRequest) |
| 48 | + return |
| 49 | + } |
| 50 | + if req.Phone == "" { |
| 51 | + http.Error(w, "Phone number is required", http.StatusBadRequest) |
| 52 | + return |
| 53 | + } |
| 54 | + |
| 55 | + user := database.User{ |
| 56 | + Username: req.Username, |
| 57 | + Password: req.Password, |
| 58 | + Email: req.Email, |
| 59 | + Phone: req.Phone, |
| 60 | + } |
| 61 | + |
| 62 | + if result := database.DB.Create(&user); result.Error != nil { |
| 63 | + if strings.Contains(result.Error.Error(), "duplicate key") { |
| 64 | + http.Error(w, "GitHub ID already exists", http.StatusConflict) |
| 65 | + } else { |
| 66 | + log.Fatalf("failed to insert user: %v", result.Error) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + w.WriteHeader(http.StatusCreated) |
| 71 | + |
| 72 | + response := map[string]string{ |
| 73 | + "message": "User registered successfully", |
| 74 | + } |
| 75 | + |
| 76 | + jsonResponse, err := json.Marshal(response) |
| 77 | + if err != nil { |
| 78 | + http.Error(w, "Failed to create response: "+err.Error(), http.StatusInternalServerError) |
| 79 | + return |
| 80 | + } |
| 81 | + w.Header().Set("Content-Type", "application/json") |
| 82 | + w.Write(jsonResponse) |
| 83 | +} |
0 commit comments