Added some routes for users

And some fixes
This commit is contained in:
cdricms
2025-01-16 10:51:30 +01:00
parent fee9a237c4
commit 9a6e4a7565
7 changed files with 173 additions and 41 deletions

View File

@@ -61,12 +61,18 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
} }
var user core.User var user core.User
err = core.DB.NewSelect(). count, err := core.DB.NewSelect().
Model(&user). Model(&user).
Where("email = ? AND password = ?", login.Email, login.Password). Where("email = ? AND password = ?", login.Email, login.Password).
Limit(1). 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 { if err != nil {
core.JSONError{ core.JSONError{
Status: core.Error, Status: core.Error,
@@ -86,7 +92,7 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
} }
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString([]byte("hello")) signed, err := token.SignedString(MySigningKey)
if err != nil { if err != nil {
core.JSONError{ core.JSONError{
Status: core.Error, Status: core.Error,
@@ -98,14 +104,13 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
core.JSONSuccess{ core.JSONSuccess{
Status: core.Success, Status: core.Success,
Message: "JWT Created", Message: "JWT Created",
Data: map[string]string{"jwt": signed}, Data: signed,
}.Respond(w, http.StatusCreated) }.Respond(w, http.StatusCreated)
} }
func AuthJWT(next http.Handler) http.Handler { func AuthJWT(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the Authorization header is provided // Check if the Authorization header is provided
fmt.Println("Coucou")
authHeader := r.Header.Get("Authorization") authHeader := r.Header.Get("Authorization")
if authHeader == "" { if authHeader == "" {
core.JSONError{ core.JSONError{

View File

@@ -14,7 +14,7 @@ import (
func HandleGetBlog(w http.ResponseWriter, r *http.Request) { func HandleGetBlog(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
fmt.Println("salut") fmt.Println("salut")
emptyObject := make(map[string]interface{}) emptyObject := make(map[string]interface{})
emptyJSON, json_err := json.Marshal(emptyObject) 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") fmt.Println("Couldn't create the json object")
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(emptyJSON)) w.Write([]byte(emptyJSON))
return return
} }
if r.Method != http.MethodGet { if r.Method != http.MethodGet {
http.Error(w, "Wrong method", http.StatusMethodNotAllowed) http.Error(w, "Wrong method", http.StatusMethodNotAllowed)
return return
} }
blog := &core.Blog{ blog := &core.Blog{
BaseModel: bun.BaseModel{}, BaseModel: bun.BaseModel{},
BlogID: [16]byte{}, BlogID: [16]byte{},
@@ -53,6 +53,6 @@ func HandleGetBlog(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Can't use select", http.StatusNotFound) http.Error(w, "Can't use select", http.StatusNotFound)
return return
} }
w.Write([]byte(`{message: "Successfuly responded to request}`)) w.Write([]byte(`{message: "Successfuly responded to request}`))
} }

View File

@@ -36,17 +36,17 @@ const (
type User struct { type User struct {
bun.BaseModel `bun:"table:users"` bun.BaseModel `bun:"table:users"`
UserID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()"` UserID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()" json:"userId"`
FirstName string `bun:"firstname,notnull"` FirstName string `bun:"firstname,notnull" json:"firstname"`
LastName string `bun:"lastname,notnull"` LastName string `bun:"lastname,notnull" json:"lastname"`
Email string `bun:"email,unique,notnull"` Email string `bun:"email,unique,notnull" json:"email"`
Password string `bun:"password,notnull"` Password string `bun:"password,notnull" json:"password"`
Phone string `bun:"phone,notnull"` Phone string `bun:"phone,notnull" json:"phone"`
Role Role `bun:"role,notnull,default:'user'"` Role Role `bun:"role,notnull,default:'user'" json:"role"`
CreatedAt time.Time `bun:"created_at,default:current_timestamp"` CreatedAt time.Time `bun:"created_at,default:current_timestamp" json:"createdAt"`
UpdatedAt time.Time `bun:"updated_at,default:current_timestamp"` UpdatedAt time.Time `bun:"updated_at,default:current_timestamp" json:"updatedAt"`
Events []Event `bun:"m2m:events_to_users,join:User=Event"` Events []Event `bun:"m2m:events_to_users,join:User=Event" json:"events,omitempty"`
Articles []*Blog `bun:"rel:has-many,join:user_id=blog_id"` Articles []*Blog `bun:"rel:has-many,join:user_id=blog_id" json:"articles,omitempty"`
} }
type Event struct { type Event struct {

View File

@@ -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)
}

49
backend/api/get_user.go Normal file
View File

@@ -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)
}

View File

@@ -2,34 +2,65 @@ package api
import ( import (
"context" "context"
"fmt" "encoding/json"
"io"
"log" "log"
"net/http" "net/http"
core "fr.latosa-escrima/api/core" core "fr.latosa-escrima/api/core"
) )
func HandleCreateUser(w http.ResponseWriter, r *http.Request) { func HandleCreateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodPost { if r.Method != http.MethodPost {
w.WriteHeader(http.StatusCreated) core.JSONError{
w.Write([]byte(`{"message": "Resource created successfully"}`)) Status: core.Error,
Message: "This method is not allowed",
}.Respond(w, http.StatusMethodNotAllowed)
return
} }
user := &core.User{ body, err := io.ReadAll(r.Body)
FirstName: "John",
LastName: "Doe",
Email: "john.doe@example.com",
Phone: "1234567890",
Password: "1234",
}
_, err := core.DB.NewInsert().Model(user).Exec(context.Background())
if err != nil { 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") var user core.User
w.WriteHeader(http.StatusOK) err = json.Unmarshal(body, &user)
w.Write([]byte(`{"message": "Inserted the 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)
} }

View File

@@ -43,8 +43,16 @@ func main() {
mux := http.NewServeMux() mux := http.NewServeMux()
core.HandleRoutes(mux, map[string]core.Handler{ core.HandleRoutes(mux, map[string]core.Handler{
"/": {Handler: handler, Middleware: nil}, "/": {Handler: handler, Middleware: nil},
"/users/login": {Handler: api.HandleLogin, 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/new": {Handler: api.HandleCreateBlog, Middleware: nil},
"/blogs/{uuid}": {Handler: api.HandleGetBlog, Middleware: nil}, "/blogs/{uuid}": {Handler: api.HandleGetBlog, Middleware: nil},
}) })