|
| 1 | +package handler |
| 2 | + |
| 3 | +import ( |
| 4 | + "FirstCrud/internal/auth" |
| 5 | + "FirstCrud/internal/model" |
| 6 | + "encoding/json" |
| 7 | + "net/http" |
| 8 | +) |
| 9 | + |
| 10 | +type login struct { |
| 11 | + storage Storage |
| 12 | +} |
| 13 | + |
| 14 | +func newLogin(s Storage) login { |
| 15 | + return login{s} |
| 16 | +} |
| 17 | + |
| 18 | +func (l *login) login(w http.ResponseWriter, r *http.Request) { |
| 19 | + |
| 20 | + if r.Method != http.MethodPost { |
| 21 | + response := NewResponse( |
| 22 | + "METHOD NO ALLOWED", |
| 23 | + http.StatusBadRequest, "Bad Request", nil) |
| 24 | + response.ToJSON(w) |
| 25 | + return |
| 26 | + } |
| 27 | + if r.Header.Get("Authorization") == "" { |
| 28 | + response := NewResponse("MISSING TOKEN", http.StatusBadRequest, "Bad request", nil) |
| 29 | + response.ToJSON(w) |
| 30 | + return |
| 31 | + } |
| 32 | + |
| 33 | + data := model.Login{} |
| 34 | + err := json.NewDecoder(r.Body).Decode(&data) |
| 35 | + if err != nil { |
| 36 | + respose := NewResponse("JSON NO VALID", http.StatusBadRequest, "Bad Request", nil) |
| 37 | + respose.ToJSON(w) |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + if !isLoginValid(data) { |
| 42 | + response := NewResponse("Email or Password no valid", http.StatusBadRequest, "Bad Request", nil) |
| 43 | + response.ToJSON(w) |
| 44 | + return |
| 45 | + } |
| 46 | + token, err := auth.GenerateToken(&data) |
| 47 | + if err != nil { |
| 48 | + response := NewResponse("Error to generate token", http.StatusInternalServerError, "Internal Server Error", nil) |
| 49 | + response.ToJSON(w) |
| 50 | + return |
| 51 | + } |
| 52 | + dataToken := map[string]string{ |
| 53 | + "token": token, |
| 54 | + "user": data.Email, |
| 55 | + } |
| 56 | + response := NewResponse("Login OK", http.StatusOK, nil, dataToken) |
| 57 | + response.ToJSON(w) |
| 58 | + return |
| 59 | +} |
| 60 | + |
| 61 | +// Simulate a login |
| 62 | +func isLoginValid(data model.Login) bool { |
| 63 | + if data.Email == "" { |
| 64 | + return false |
| 65 | + } |
| 66 | + if data.Password == "" { |
| 67 | + return false |
| 68 | + } |
| 69 | + return data. Email == "[email protected]" && data. Password == "123456" |
| 70 | +} |
0 commit comments