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
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{

View File

@@ -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 {

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 (
"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)
}

View File

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