Reorganization of backend + new routes
This commit is contained in:
3
backend/core/csrf.go
Normal file
3
backend/core/csrf.go
Normal file
@@ -0,0 +1,3 @@
|
||||
package core
|
||||
|
||||
var CSRF_KEY = []byte("32-byte-long-auth-key")
|
||||
24
backend/core/models/blogs.go
Normal file
24
backend/core/models/blogs.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type Blog struct {
|
||||
bun.BaseModel `bun:"table:blogs"`
|
||||
|
||||
BlogID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()" json:"blogID"`
|
||||
Slug string `bun:"slug,unique,notnull" json:"slug"`
|
||||
Content string `bun:"content,notnull" json:"content"`
|
||||
Label string `bun:"label" json:"label"`
|
||||
AuthorID uuid.UUID `bun:"author_id,type:uuid,notnull" json:"authorID"`
|
||||
Published time.Time `bun:"published,default:current_timestamp" json:"published"`
|
||||
Summary string `bun:"summary" json:"summary"`
|
||||
Image string `bun:"image" json:"image"`
|
||||
Href string `bun:"href" json:"href"`
|
||||
|
||||
Author User `bun:"rel:belongs-to,join:author_id=user_id" json:"author"`
|
||||
}
|
||||
25
backend/core/models/events.go
Normal file
25
backend/core/models/events.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
Active Status = "Active"
|
||||
Inactive Status = "Inactive"
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
bun.BaseModel `bun:"table:events"`
|
||||
|
||||
EventID uuid.UUID `bun:"event_id,type:uuid,pk,default:gen_random_uuid()" json:"id"`
|
||||
CreationDate time.Time `bun:"creation_date,notnull,default:current_timestamp" json:"creationDate"`
|
||||
ScheduleStart time.Time `bun:"schedule_start,notnull" json:"start"`
|
||||
ScheduleEnd time.Time `bun:"schedule_end,notnull" json:"end"`
|
||||
Status Status `bun:"status,notnull,default:'Inactive'" json:"status"`
|
||||
}
|
||||
16
backend/core/models/events_to_user.go
Normal file
16
backend/core/models/events_to_user.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type EventToUser struct {
|
||||
bun.BaseModel `bun:"table:events_to_users"`
|
||||
|
||||
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"`
|
||||
User *User `bun:"rel:belongs-to,join:user_id=user_id"`
|
||||
}
|
||||
8
backend/core/models/main.go
Normal file
8
backend/core/models/main.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package models
|
||||
|
||||
type Group string
|
||||
|
||||
const (
|
||||
LatosaGroup Group = "latosa"
|
||||
WingTsunGroup Group = "wing-tsun"
|
||||
)
|
||||
18
backend/core/models/media.go
Normal file
18
backend/core/models/media.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type Media struct {
|
||||
bun.BaseModel `bun:"table:media"`
|
||||
ID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()" json:"id"`
|
||||
AuthorID uuid.UUID `bun:"author_id,type:uuid,notnull" json:"authorID"`
|
||||
Author *User `bun:"rel:belongs-to,join:author_id=user_id" json:"author,omitempty"`
|
||||
Type string `bun:"media_type" json:"type"` // Image, Video, GIF etc. Add support for PDFs?
|
||||
Alt string `bun:"media_alt" json:"alt"`
|
||||
Path string `bun:"media_path" json:"path"`
|
||||
Size int64 `bun:"media_size" json:"size"`
|
||||
URL string `bun:"-" json:"url"`
|
||||
}
|
||||
15
backend/core/models/permissions.go
Normal file
15
backend/core/models/permissions.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package models
|
||||
|
||||
import "github.com/uptrace/bun"
|
||||
|
||||
type PermissionConditions struct {
|
||||
Groups *[]Group `json:"groups,omitempty"`
|
||||
}
|
||||
|
||||
type Permission struct {
|
||||
bun.BaseModel `bun:"table:permissions"`
|
||||
ID int `bun:"id,pk,autoincrement" json:"id"`
|
||||
Resource string `bun:"resource,notnull,unique:permission" json:"resource"`
|
||||
Action string `bun:"action,notnull,unique:permission" json:"action"`
|
||||
Conditions PermissionConditions `bun:"conditions,type:jsonb" json:"conditions"`
|
||||
}
|
||||
16
backend/core/models/permissions_to_roles.go
Normal file
16
backend/core/models/permissions_to_roles.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type PermissionToRole struct {
|
||||
bun.BaseModel `bun:"table:permissions_to_users"`
|
||||
|
||||
PermissionID int `bun:"permission_id,pk"`
|
||||
RoleID uuid.UUID `bun:"type:uuid,pk"`
|
||||
|
||||
Permission *Permission `bun:"rel:belongs-to,join:permission_id=id"`
|
||||
Role *Role `bun:"rel:belongs-to,join:role_id=id"`
|
||||
}
|
||||
14
backend/core/models/roles.go
Normal file
14
backend/core/models/roles.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
bun.BaseModel `bun:"table:roles"`
|
||||
ID uuid.UUID `bun:"id,pk,type:uuid,default:gen_random_uuid()" json:"id"`
|
||||
Name string `bun:"name,unique,notnull" json:"name"`
|
||||
|
||||
Permissions []Permission `bun:"m2m:permissions_to_users,join:Role=Permission" json:"permissions,omitempty"`
|
||||
}
|
||||
36
backend/core/models/shortcodes.go
Normal file
36
backend/core/models/shortcodes.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type ShortcodeType string
|
||||
|
||||
const (
|
||||
ShortcodeMedia ShortcodeType = "media"
|
||||
ShortcodeValue ShortcodeType = "value"
|
||||
)
|
||||
|
||||
type Shortcode struct {
|
||||
bun.BaseModel `bun:"table:shortcodes,alias:sc"`
|
||||
|
||||
ID int64 `bun:"id,pk,autoincrement" json:"id"` // Primary key
|
||||
Code string `bun:"code,notnull,unique" json:"code"` // The shortcode value
|
||||
Type ShortcodeType `bun:"shortcode_type,notnull" json:"type"`
|
||||
Value *string `bun:"value" json:"value,omitempty"`
|
||||
MediaID *uuid.UUID `bun:"media_id,type:uuid" json:"media_id,omitempty"` // Nullable reference to another table's ID
|
||||
Media *Media `bun:"rel:belongs-to,join:media_id=id" json:"media,omitempty"` // Relation to Media
|
||||
}
|
||||
|
||||
func (s *Shortcode) Validate() error {
|
||||
if s.Value != nil && s.MediaID != nil {
|
||||
return errors.New("both value and media_id cannot be set at the same time")
|
||||
}
|
||||
if s.Value == nil && s.MediaID == nil {
|
||||
return errors.New("either value or media_id must be set")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
60
backend/core/models/users.go
Normal file
60
backend/core/models/users.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type UserAttributes struct {
|
||||
Groups []Group `json:"groups"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
bun.BaseModel `bun:"table:users"`
|
||||
|
||||
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,omitempty"`
|
||||
Phone string `bun:"phone,notnull" json:"phone"`
|
||||
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"`
|
||||
Attributes UserAttributes `bun:"attributes,type:jsonb" json:"attributes"`
|
||||
Roles []Role `bun:"m2m:users_to_roles,join:User=Role" json:"roles,omitempty"`
|
||||
}
|
||||
|
||||
func (u *User) Insert(db *bun.DB, 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(db *bun.DB, ctx context.Context, email, password string) (*User, error) {
|
||||
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
|
||||
}
|
||||
16
backend/core/models/users_to_roles.go
Normal file
16
backend/core/models/users_to_roles.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type UserToRole struct {
|
||||
bun.BaseModel `bun:"table:users_to_roles"`
|
||||
|
||||
UserID uuid.UUID `bun:"user_id,type:uuid,pk"`
|
||||
RoleID uuid.UUID `bun:"type:uuid,pk"`
|
||||
|
||||
User *User `bun:"rel:belongs-to,join:user_id=user_id"`
|
||||
Role *Role `bun:"rel:belongs-to,join:role_id=id"`
|
||||
}
|
||||
13
backend/core/models/website_settings.go
Normal file
13
backend/core/models/website_settings.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type WebsiteSettings struct {
|
||||
bun.BaseModel `bun:"table:website_settings"`
|
||||
|
||||
ID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()" json:"id"`
|
||||
AutoAcceptDemand bool `bun:"auto_accept_demand,default:false" json:"autoAcceptDemand"`
|
||||
}
|
||||
8
backend/core/paginated.go
Normal file
8
backend/core/paginated.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package core
|
||||
|
||||
type Paginated[T any] struct {
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
TotalPages int `json:"totalPages"`
|
||||
Items []T `json:"items"`
|
||||
}
|
||||
61
backend/core/permissions.go
Normal file
61
backend/core/permissions.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"fr.latosa-escrima/core/models"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type Permissions []models.Permission
|
||||
|
||||
func GetAllPermissions() Permissions {
|
||||
resources := []string{"users", "roles", "media", "events", "permissions", "shortcodes", "blogs"}
|
||||
var perms Permissions
|
||||
for _, resource := range resources {
|
||||
perms = append(perms, Permissions{
|
||||
{
|
||||
Resource: resource,
|
||||
Action: "insert",
|
||||
},
|
||||
{
|
||||
Resource: resource,
|
||||
Action: "update",
|
||||
},
|
||||
{
|
||||
Resource: resource,
|
||||
Action: "delete",
|
||||
},
|
||||
{
|
||||
Resource: resource,
|
||||
Action: "get",
|
||||
},
|
||||
{
|
||||
Resource: resource,
|
||||
Action: "own:insert",
|
||||
},
|
||||
{
|
||||
Resource: resource,
|
||||
Action: "own:update",
|
||||
},
|
||||
{
|
||||
Resource: resource,
|
||||
Action: "own:delete",
|
||||
},
|
||||
{
|
||||
Resource: resource,
|
||||
Action: "own:get",
|
||||
},
|
||||
}...)
|
||||
}
|
||||
return perms
|
||||
}
|
||||
|
||||
func (perms Permissions) InsertAll(db *bun.DB, ctx context.Context) error {
|
||||
_, err := db.NewInsert().
|
||||
Model(&perms).
|
||||
Ignore().
|
||||
Exec(ctx)
|
||||
|
||||
return err
|
||||
}
|
||||
77
backend/core/router.go
Normal file
77
backend/core/router.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type JSONStatus string
|
||||
|
||||
const (
|
||||
Error JSONStatus = "Error"
|
||||
Success JSONStatus = "Success"
|
||||
)
|
||||
|
||||
type JSONResponse interface {
|
||||
ToJSON() ([]byte, error)
|
||||
Respond(w http.ResponseWriter, code int)
|
||||
}
|
||||
|
||||
type JSONError struct {
|
||||
Status JSONStatus `json:"status"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type JSONSuccess struct {
|
||||
Status JSONStatus `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func (r *JSONError) ToJSON() ([]byte, error) {
|
||||
return json.Marshal(r)
|
||||
}
|
||||
|
||||
func (r *JSONSuccess) ToJSON() ([]byte, error) {
|
||||
return json.Marshal(r)
|
||||
}
|
||||
|
||||
func defaultResponse(r JSONResponse, w http.ResponseWriter, code int) {
|
||||
jsonData, err := r.ToJSON()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotAcceptable)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
w.Write(jsonData)
|
||||
}
|
||||
|
||||
func (r JSONError) Respond(w http.ResponseWriter, code int) {
|
||||
defaultResponse(&r, w, code)
|
||||
}
|
||||
|
||||
func (r JSONSuccess) Respond(w http.ResponseWriter, code int) {
|
||||
defaultResponse(&r, w, code)
|
||||
}
|
||||
|
||||
type Middleware func(http.Handler) http.Handler
|
||||
|
||||
type Handler struct {
|
||||
Handler http.HandlerFunc
|
||||
Middlewares []Middleware
|
||||
}
|
||||
|
||||
func HandleRoutes(mux *http.ServeMux, routes map[string]Handler) {
|
||||
for pattern, handler := range routes {
|
||||
if handler.Middlewares == nil {
|
||||
mux.HandleFunc(pattern, handler.Handler)
|
||||
} else {
|
||||
h := http.HandlerFunc(handler.Handler)
|
||||
for _, middleware := range handler.Middlewares {
|
||||
h = http.HandlerFunc(middleware(h).ServeHTTP)
|
||||
}
|
||||
mux.Handle(pattern, h)
|
||||
}
|
||||
}
|
||||
}
|
||||
64
backend/core/schemas.go
Normal file
64
backend/core/schemas.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/uptrace/bun"
|
||||
"github.com/uptrace/bun/dialect/pgdialect"
|
||||
"github.com/uptrace/bun/driver/pgdriver"
|
||||
|
||||
m "fr.latosa-escrima/core/models"
|
||||
)
|
||||
|
||||
var DB *bun.DB
|
||||
|
||||
type DSN struct {
|
||||
Hostname string
|
||||
Port string
|
||||
DBName string
|
||||
User string
|
||||
Password string
|
||||
}
|
||||
|
||||
func (dsn *DSN) ToString() string {
|
||||
return fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable", dsn.User, dsn.Password, dsn.Hostname, dsn.Port, dsn.DBName)
|
||||
}
|
||||
|
||||
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((*m.EventToUser)(nil))
|
||||
db.RegisterModel((*m.PermissionToRole)(nil))
|
||||
db.RegisterModel((*m.UserToRole)(nil))
|
||||
_, err = db.NewCreateTable().Model((*m.User)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.Event)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.EventToUser)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.Blog)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.WebsiteSettings)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.Media)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.Shortcode)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.Role)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.Permission)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.PermissionToRole)(nil)).IfNotExists().Exec(ctx)
|
||||
_, err = db.NewCreateTable().Model((*m.UserToRole)(nil)).IfNotExists().Exec(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
perms := GetAllPermissions()
|
||||
err = perms.InsertAll(db, ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
Reference in New Issue
Block a user