diff --git a/backend/api/auth.go b/backend/api/auth.go index a1444fb..c1b03e5 100644 --- a/backend/api/auth.go +++ b/backend/api/auth.go @@ -61,12 +61,18 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) { } var user core.User - err = core.DB.NewSelect(). + count, err := core.DB.NewSelect(). Model(&user). Where("email = ? AND password = ?", login.Email, login.Password). Limit(1). - Scan(context.Background()) - + ScanAndCount(context.Background()) + if count == 0 { + core.JSONError{ + Status: core.Error, + Message: "User not found.", + }.Respond(w, http.StatusNotFound) + return + } if err != nil { core.JSONError{ Status: core.Error, @@ -86,7 +92,7 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) { } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - signed, err := token.SignedString([]byte("hello")) + signed, err := token.SignedString(MySigningKey) if err != nil { core.JSONError{ Status: core.Error, @@ -98,14 +104,13 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) { core.JSONSuccess{ Status: core.Success, Message: "JWT Created", - Data: map[string]string{"jwt": signed}, + Data: signed, }.Respond(w, http.StatusCreated) } func AuthJWT(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Check if the Authorization header is provided - fmt.Println("Coucou") authHeader := r.Header.Get("Authorization") if authHeader == "" { core.JSONError{ diff --git a/backend/api/blogs.go b/backend/api/blogs.go index ac128ba..3bcffbb 100644 --- a/backend/api/blogs.go +++ b/backend/api/blogs.go @@ -14,7 +14,7 @@ import ( func HandleGetBlog(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") - fmt.Println("salut") + fmt.Println("salut") emptyObject := make(map[string]interface{}) emptyJSON, json_err := json.Marshal(emptyObject) @@ -22,14 +22,14 @@ func HandleGetBlog(w http.ResponseWriter, r *http.Request) { fmt.Println("Couldn't create the json object") w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(emptyJSON)) - return + return } if r.Method != http.MethodGet { http.Error(w, "Wrong method", http.StatusMethodNotAllowed) return } - + blog := &core.Blog{ BaseModel: bun.BaseModel{}, BlogID: [16]byte{}, @@ -53,6 +53,6 @@ func HandleGetBlog(w http.ResponseWriter, r *http.Request) { http.Error(w, "Can't use select", http.StatusNotFound) return } - + w.Write([]byte(`{message: "Successfuly responded to request}`)) } diff --git a/backend/api/core/schemas.go b/backend/api/core/schemas.go index a9a937b..92062c7 100644 --- a/backend/api/core/schemas.go +++ b/backend/api/core/schemas.go @@ -36,17 +36,17 @@ const ( type User struct { bun.BaseModel `bun:"table:users"` - UserID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()"` - FirstName string `bun:"firstname,notnull"` - LastName string `bun:"lastname,notnull"` - Email string `bun:"email,unique,notnull"` - Password string `bun:"password,notnull"` - Phone string `bun:"phone,notnull"` - Role Role `bun:"role,notnull,default:'user'"` - CreatedAt time.Time `bun:"created_at,default:current_timestamp"` - UpdatedAt time.Time `bun:"updated_at,default:current_timestamp"` - Events []Event `bun:"m2m:events_to_users,join:User=Event"` - Articles []*Blog `bun:"rel:has-many,join:user_id=blog_id"` + UserID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()" json:"userId"` + FirstName string `bun:"firstname,notnull" json:"firstname"` + LastName string `bun:"lastname,notnull" json:"lastname"` + Email string `bun:"email,unique,notnull" json:"email"` + Password string `bun:"password,notnull" json:"password"` + Phone string `bun:"phone,notnull" json:"phone"` + Role Role `bun:"role,notnull,default:'user'" json:"role"` + CreatedAt time.Time `bun:"created_at,default:current_timestamp" json:"createdAt"` + UpdatedAt time.Time `bun:"updated_at,default:current_timestamp" json:"updatedAt"` + Events []Event `bun:"m2m:events_to_users,join:User=Event" json:"events,omitempty"` + Articles []*Blog `bun:"rel:has-many,join:user_id=blog_id" json:"articles,omitempty"` } type Event struct { diff --git a/backend/api/delete_user.go b/backend/api/delete_user.go new file mode 100644 index 0000000..996c89d --- /dev/null +++ b/backend/api/delete_user.go @@ -0,0 +1,39 @@ +package api + +import ( + "context" + "net/http" + + "fr.latosa-escrima/api/core" +) + +func HandleDeleteUser(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodDelete { + core.JSONError{ + Status: core.Error, + Message: "Method is not allowed.", + }.Respond(w, http.StatusMethodNotAllowed) + return + } + + uuid := r.PathValue("user_uuid") + _, err := core.DB.NewDelete(). + Model((*core.User)(nil)). + Where("user_id = ?", uuid). + Exec(context.Background()) + + if err != nil { + core.JSONError{ + Status: core.Error, + Message: err.Error(), + }.Respond(w, http.StatusInternalServerError) + return + } + + // TODO : Remove password + core.JSONSuccess{ + Status: core.Success, + Message: "User deleted.", + Data: nil, + }.Respond(w, http.StatusOK) +} diff --git a/backend/api/get_user.go b/backend/api/get_user.go new file mode 100644 index 0000000..f8a55f5 --- /dev/null +++ b/backend/api/get_user.go @@ -0,0 +1,49 @@ +package api + +import ( + "context" + "net/http" + + "fr.latosa-escrima/api/core" +) + +func HandleGetUser(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + core.JSONError{ + Status: core.Error, + Message: "Method is not allowed.", + }.Respond(w, http.StatusMethodNotAllowed) + return + } + + uuid := r.PathValue("user_uuid") + var user core.User + count, err := core.DB.NewSelect(). + Model(&user). + Where("user_id = ?", uuid). + Limit(1). + ScanAndCount(context.Background()) + + if count == 0 { + core.JSONError{ + Status: core.Error, + Message: "User not found.", + }.Respond(w, http.StatusNotFound) + return + } + + if err != nil { + core.JSONError{ + Status: core.Error, + Message: err.Error(), + }.Respond(w, http.StatusInternalServerError) + return + } + + // TODO : Remove password + core.JSONSuccess{ + Status: core.Success, + Message: "User found.", + Data: user, + }.Respond(w, http.StatusOK) +} diff --git a/backend/api/new_user.go b/backend/api/new_user.go index 63ce902..7d42873 100644 --- a/backend/api/new_user.go +++ b/backend/api/new_user.go @@ -2,34 +2,65 @@ package api import ( "context" - "fmt" + "encoding/json" + "io" "log" "net/http" + core "fr.latosa-escrima/api/core" ) func HandleCreateUser(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - + if r.Method != http.MethodPost { - w.WriteHeader(http.StatusCreated) - w.Write([]byte(`{"message": "Resource created successfully"}`)) + core.JSONError{ + Status: core.Error, + Message: "This method is not allowed", + }.Respond(w, http.StatusMethodNotAllowed) + return } - user := &core.User{ - FirstName: "John", - LastName: "Doe", - Email: "john.doe@example.com", - Phone: "1234567890", - Password: "1234", - } - - _, err := core.DB.NewInsert().Model(user).Exec(context.Background()) + body, err := io.ReadAll(r.Body) if err != nil { - log.Fatal(err) + core.JSONError{ + Status: core.Error, + Message: "The body of your message is invalid.", + }.Respond(w, http.StatusNotAcceptable) + return } - fmt.Println("User inserted successfully") - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"message": "Inserted the user"}`)) + var user core.User + err = json.Unmarshal(body, &user) + if err != nil { + core.JSONError{ + Status: core.Error, + Message: "It seems your body in invalid JSON.", + }.Respond(w, http.StatusNotAcceptable) + return + } + + log.Println(user) + + res, err := core.DB.NewInsert().Model(user).Exec(context.Background()) + if res == nil { + core.JSONError{ + Status: core.Error, + Message: "The user couldn't be inserted.", + }.Respond(w, http.StatusNotAcceptable) + return + } + + if err != nil { + core.JSONError{ + Status: core.Error, + Message: err.Error(), + }.Respond(w, http.StatusInternalServerError) + return + } + + core.JSONSuccess{ + Status: core.Success, + Message: "User inserted successfully.", + Data: nil, + }.Respond(w, http.StatusCreated) } diff --git a/backend/main.go b/backend/main.go index 4e2a266..72869eb 100644 --- a/backend/main.go +++ b/backend/main.go @@ -43,8 +43,16 @@ func main() { mux := http.NewServeMux() core.HandleRoutes(mux, map[string]core.Handler{ - "/": {Handler: handler, Middleware: nil}, - "/users/login": {Handler: api.HandleLogin, Middleware: nil}, + "/": {Handler: handler, Middleware: nil}, + "/users/login": {Handler: api.HandleLogin, Middleware: nil}, + "/users/new": {Handler: api.HandleCreateUser, Middleware: api.AuthJWT}, + "/users/{user_uuid}": {Handler: api.HandleGetUser, Middleware: api.AuthJWT}, + "/users/{user_uuid}/delete": {Handler: api.HandleDeleteUser, Middleware: api.AuthJWT}, + // "/users/{user_uuid}/update": {Handler: api.HandleUpdateUser, Middleware: api.AuthJWT}, + // "/users/{user_uuid}/events": {Handler: nil, Middleware: nil}, + // "/users/{user_uuid}/events/{event_uuid}": {Handler: nil, Middleware: nil}, + // "/users/{user_uuid}/events/{event_uuid}/delete": {Handler: nil, Middleware: nil}, + // "/users/{user_uuid}/events/{event_uuid}/update": {Handler: nil, Middleware: nil}, "/blogs/new": {Handler: api.HandleCreateBlog, Middleware: nil}, "/blogs/{uuid}": {Handler: api.HandleGetBlog, Middleware: nil}, })