Merge branch 'dev/cedric' into dev/guerby

This commit is contained in:
gom-by
2025-01-17 15:40:06 +01:00
26 changed files with 515 additions and 97 deletions

View File

@@ -53,13 +53,8 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
return
}
var user core.User
count, err := core.DB.NewSelect().
Model(&user).
Where("email = ? AND password = ?", login.Email, login.Password).
Limit(1).
ScanAndCount(context.Background())
if count == 0 {
user, err := core.Verify(context.Background(), login.Email, login.Password)
if user == nil {
core.JSONError{
Status: core.Error,
Message: "User not found.",
@@ -140,8 +135,10 @@ func AuthJWT(next http.Handler) http.Handler {
return
}
ctx := context.WithValue(r.Context(), "token", token)
// Call the next handler if the JWT is valid
next.ServeHTTP(w, r)
next.ServeHTTP(w, r.WithContext(ctx))
})
}

View File

@@ -36,8 +36,8 @@ const (
type Status string
const (
Active Status = "Active"
Inactive Status = "Inactive"
Active Status = "Active"
Inactive Status = "Inactive"
)
type User struct {
@@ -56,6 +56,43 @@ type User struct {
Articles []*Blog `bun:"rel:has-many,join:user_id=blog_id" json:"articles,omitempty"`
}
func (u *User) Insert(ctx context.Context) (sql.Result, error) {
u.Password = fmt.Sprintf("crypt('%s', gen_salt('bf'))", u.Password)
return DB.NewInsert().
Model(u).
Value("password", u.Password).
Exec(ctx)
}
func Verify(ctx context.Context, email, password string) (*User, error) {
// var user User
// query := `
// SELECT *
// FROM users
// WHERE email = ? AND password = crypt(?, password)
// `
//
// err := DB.NewRaw(query, email, password).Scan(ctx, user)
var user User
count, err := DB.NewSelect().
Model(&user).
Where("email = ? AND password = crypt(?, password)", email, password).
Limit(1).
ScanAndCount(context.Background())
if count == 0 {
return nil, fmt.Errorf("invalid email or password")
}
if err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("invalid email or password")
}
return nil, err
}
return &user, nil
}
type Event struct {
bun.BaseModel `bun:"table:events"`
@@ -69,7 +106,7 @@ type Event struct {
type EventToUser struct {
bun.BaseModel `bun:"table:events_to_users"`
EventID uuid.UUID `bun:"type:uuid,pk"`
EventID uuid.UUID `bun:"type:uuid,pk"`
UserID uuid.UUID `bun:"type:uuid,pk"`
Event *Event `bun:"rel:belongs-to,join:event_id=event_id"`
@@ -103,12 +140,18 @@ func InitDatabase(dsn DSN) (*bun.DB, error) {
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn.ToString())))
db := bun.NewDB(sqldb, pgdialect.New())
ctx := context.Background()
_, err := db.ExecContext(ctx, "CREATE EXTENSION IF NOT EXISTS pgcrypto;")
if err != nil {
return nil, err
}
db.RegisterModel((*EventToUser)(nil))
_, err := db.NewCreateTable().Model((*User)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*Event)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*EventToUser)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*Blog)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*WebsiteSettings)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*User)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*Event)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*EventToUser)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*Blog)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*WebsiteSettings)(nil)).IfNotExists().Exec(ctx)
if err != nil {
return nil, err
}

33
backend/api/get_me.go Normal file
View File

@@ -0,0 +1,33 @@
package api
import (
"net/http"
"fr.latosa-escrima/api/core"
"github.com/golang-jwt/jwt/v5"
)
func HandleGetMe(w http.ResponseWriter, r *http.Request) {
token, ok := r.Context().Value("token").(*jwt.Token)
if !ok {
core.JSONError{
Status: core.Error,
Message: "Couldn't retrieve your JWT.",
}.Respond(w, http.StatusInternalServerError)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
core.JSONError{
Status: core.Error,
Message: "Invalid token claims.",
}.Respond(w, http.StatusInternalServerError)
return
}
uuid := claims["user_id"].(string)
r.SetPathValue("user_uuid", uuid)
HandleGetUser(w, r)
}

View File

@@ -17,7 +17,7 @@ func HandleCreateBlog(w http.ResponseWriter, r *http.Request) {
}.Respond(w, http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
core.JSONError{
@@ -26,16 +26,16 @@ func HandleCreateBlog(w http.ResponseWriter, r *http.Request) {
}.Respond(w, http.StatusNoContent)
return
}
var blog core.Blog
var blog core.Blog
if err = json.Unmarshal(body, &blog); err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
}
_, err = core.DB.NewInsert().Model(blog).Exec(context.Background())
_, err = core.DB.NewInsert().Model(blog).Exec(context.Background())
if err != nil {
core.JSONError{
Status: core.Error,
@@ -46,6 +46,6 @@ func HandleCreateBlog(w http.ResponseWriter, r *http.Request) {
core.JSONSuccess{
Status: core.Success,
Message: "Blog inserted",
Data: blog,
Data: blog,
}.Respond(w, http.StatusCreated)
}

View File

@@ -32,14 +32,15 @@ func HandleCreateUser(w http.ResponseWriter, r *http.Request) {
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
}
res, err := user.Insert(context.Background())
log.Println(res)
// 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{

View File

@@ -49,6 +49,7 @@ func HandleUpdateUser(w http.ResponseWriter, r *http.Request) {
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldname := typ.Field(i).Name
tag := typ.Field(i).Tag.Get("bun")
if tag == "" {
@@ -57,7 +58,11 @@ func HandleUpdateUser(w http.ResponseWriter, r *http.Request) {
// Only add fields that are non-nil and non-zero
if field.IsValid() && !field.IsNil() && !field.IsZero() {
updateQuery.Set(fmt.Sprintf("%s = ?", strings.Split(tag, ",")[0]), field.Interface())
if fieldname == "Password" {
updateQuery.Set(fmt.Sprintf("%s = crypt(?, gen_salt('bf'))", strings.Split(tag, ",")[0]), field.Interface())
} else {
updateQuery.Set(fmt.Sprintf("%s = ?", strings.Split(tag, ",")[0]), field.Interface())
}
}
}