forked from mirrors/homebox
end-to-end testing setup
This commit is contained in:
parent
b4eb7d8ddc
commit
ad4c8c9ab4
41 changed files with 544 additions and 313 deletions
|
@ -1,24 +0,0 @@
|
|||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
README.md
|
|
@ -1,23 +0,0 @@
|
|||
# Build API
|
||||
FROM golang:alpine AS builder
|
||||
RUN apk add --no-cache git build-base
|
||||
WORKDIR /go/src/app
|
||||
COPY . .
|
||||
RUN go get -d -v ./...
|
||||
RUN go build -o /go/bin/api -v ./app/api/*.go
|
||||
|
||||
|
||||
# Production Stage
|
||||
FROM alpine:latest
|
||||
|
||||
RUN apk --no-cache add ca-certificates
|
||||
COPY ./config.template.yml /app/config.yml
|
||||
COPY --from=builder /go/bin/api /app
|
||||
|
||||
RUN chmod +x /app/api
|
||||
RUN chmod +x /bin/manage
|
||||
|
||||
LABEL Name=gowebtemplate Version=0.0.1
|
||||
EXPOSE 7745
|
||||
WORKDIR /app
|
||||
CMD [ "./api" ]
|
|
@ -36,7 +36,7 @@ func NewApp(conf *config.Config) *app {
|
|||
return s
|
||||
}
|
||||
|
||||
func (a *app) StartReoccurringTasks(t time.Duration, fn func()) {
|
||||
func (a *app) StartBgTask(t time.Duration, fn func()) {
|
||||
for {
|
||||
a.server.Background(fn)
|
||||
time.Sleep(t)
|
||||
|
|
|
@ -1,40 +0,0 @@
|
|||
package base
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/content/backend/internal/types"
|
||||
"github.com/hay-kot/content/backend/pkgs/server"
|
||||
)
|
||||
|
||||
type ReadyFunc func() bool
|
||||
|
||||
type BaseController struct {
|
||||
svr *server.Server
|
||||
}
|
||||
|
||||
func NewBaseController(svr *server.Server) *BaseController {
|
||||
h := &BaseController{
|
||||
svr: svr,
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// HandleBase godoc
|
||||
// @Summary Retrieves the basic information about the API
|
||||
// @Tags Base
|
||||
// @Produce json
|
||||
// @Success 200 {object} server.Result{item=types.ApiSummary}
|
||||
// @Router /status [GET]
|
||||
func (ctrl *BaseController) HandleBase(ready ReadyFunc, versions ...string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
data := types.ApiSummary{
|
||||
Healthy: ready(),
|
||||
Versions: versions,
|
||||
Title: "Go API Template",
|
||||
Message: "Welcome to the Go API Template Application!",
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusOK, server.Wrap(data))
|
||||
}
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
package base
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func GetTestHandler(t *testing.T) *BaseController {
|
||||
return NewBaseController(nil)
|
||||
}
|
||||
|
||||
func TestHandlersv1_HandleBase(t *testing.T) {
|
||||
// Setup
|
||||
hdlrFunc := GetTestHandler(t).HandleBase(func() bool { return true }, "v1")
|
||||
|
||||
// Call Handler Func
|
||||
rr := httptest.NewRecorder()
|
||||
hdlrFunc(rr, nil)
|
||||
|
||||
// Validate Status Code
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("Expected status code to be %d, got %d", http.StatusOK, rr.Code)
|
||||
}
|
||||
|
||||
// Validate Json Payload
|
||||
expected := `{"item":{"health":true,"versions":["v1"],"title":"Go API Template","message":"Welcome to the Go API Template Application!"}}`
|
||||
|
||||
if rr.Body.String() != expected {
|
||||
t.Errorf("Expected json to be %s, got %s", expected, rr.Body.String())
|
||||
}
|
||||
|
||||
}
|
|
@ -21,37 +21,6 @@ const docTemplate = `{
|
|||
"host": "{{.Host}}",
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/status": {
|
||||
"get": {
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Base"
|
||||
],
|
||||
"summary": "Retrieves the basic information about the API",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/server.Result"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"item": {
|
||||
"$ref": "#/definitions/types.ApiSummary"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/items": {
|
||||
"get": {
|
||||
"security": [
|
||||
|
@ -544,6 +513,25 @@ const docTemplate = `{
|
|||
}
|
||||
}
|
||||
},
|
||||
"/v1/status": {
|
||||
"get": {
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Base"
|
||||
],
|
||||
"summary": "Retrieves the basic information about the API",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.ApiSummary"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/users/login": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
|
@ -726,6 +714,25 @@ const docTemplate = `{
|
|||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"User"
|
||||
],
|
||||
"summary": "Deletes the user account",
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/users/self/password": {
|
||||
|
|
|
@ -13,37 +13,6 @@
|
|||
},
|
||||
"basePath": "/api",
|
||||
"paths": {
|
||||
"/status": {
|
||||
"get": {
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Base"
|
||||
],
|
||||
"summary": "Retrieves the basic information about the API",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/server.Result"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"item": {
|
||||
"$ref": "#/definitions/types.ApiSummary"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/items": {
|
||||
"get": {
|
||||
"security": [
|
||||
|
@ -536,6 +505,25 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/v1/status": {
|
||||
"get": {
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Base"
|
||||
],
|
||||
"summary": "Retrieves the basic information about the API",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.ApiSummary"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/users/login": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
|
@ -718,6 +706,25 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"User"
|
||||
],
|
||||
"summary": "Deletes the user account",
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/users/self/password": {
|
||||
|
|
|
@ -580,23 +580,6 @@ info:
|
|||
title: Go API Templates
|
||||
version: "1.0"
|
||||
paths:
|
||||
/status:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/definitions/server.Result'
|
||||
- properties:
|
||||
item:
|
||||
$ref: '#/definitions/types.ApiSummary'
|
||||
type: object
|
||||
summary: Retrieves the basic information about the API
|
||||
tags:
|
||||
- Base
|
||||
/v1/items:
|
||||
get:
|
||||
produces:
|
||||
|
@ -888,6 +871,18 @@ paths:
|
|||
summary: updates a location
|
||||
tags:
|
||||
- Locations
|
||||
/v1/status:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/types.ApiSummary'
|
||||
summary: Retrieves the basic information about the API
|
||||
tags:
|
||||
- Base
|
||||
/v1/users/login:
|
||||
post:
|
||||
consumes:
|
||||
|
@ -955,6 +950,17 @@ paths:
|
|||
tags:
|
||||
- User
|
||||
/v1/users/self:
|
||||
delete:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Deletes the user account
|
||||
tags:
|
||||
- User
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
|
|
|
@ -30,6 +30,7 @@ func main() {
|
|||
// Logger Init
|
||||
// zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
||||
log.Level(zerolog.DebugLevel)
|
||||
|
||||
cfgFile := "config.yml"
|
||||
|
||||
|
@ -89,7 +90,7 @@ func run(cfg *config.Config) error {
|
|||
// =========================================================================
|
||||
// Start Reoccurring Tasks
|
||||
|
||||
go app.StartReoccurringTasks(time.Duration(24)*time.Hour, func() {
|
||||
go app.StartBgTask(time.Duration(24)*time.Hour, func() {
|
||||
_, err := app.repos.AuthTokens.PurgeExpiredTokens(context.Background())
|
||||
if err != nil {
|
||||
log.Error().
|
||||
|
|
0
backend/app/api/public/.gitkeep
Normal file
0
backend/app/api/public/.gitkeep
Normal file
|
@ -1,17 +1,27 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/hay-kot/content/backend/app/api/base"
|
||||
_ "github.com/hay-kot/content/backend/app/api/docs"
|
||||
v1 "github.com/hay-kot/content/backend/app/api/v1"
|
||||
"github.com/hay-kot/content/backend/internal/repo"
|
||||
"github.com/rs/zerolog/log"
|
||||
httpSwagger "github.com/swaggo/http-swagger" // http-swagger middleware
|
||||
)
|
||||
|
||||
//go:embed all:public/*
|
||||
var public embed.FS
|
||||
|
||||
const prefix = "/api"
|
||||
|
||||
// registerRoutes registers all the routes for the API
|
||||
|
@ -22,54 +32,54 @@ func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux {
|
|||
// =========================================================================
|
||||
// Base Routes
|
||||
|
||||
DumpEmbedContents()
|
||||
|
||||
r.Get("/swagger/*", httpSwagger.Handler(
|
||||
httpSwagger.URL(fmt.Sprintf("%s://%s/swagger/doc.json", a.conf.Swagger.Scheme, a.conf.Swagger.Host)),
|
||||
))
|
||||
|
||||
// Server Favicon
|
||||
r.Get("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "static/favicon.ico")
|
||||
})
|
||||
|
||||
baseHandler := base.NewBaseController(a.server)
|
||||
r.Get(prefix+"/status", baseHandler.HandleBase(func() bool { return true }, "v1"))
|
||||
|
||||
// =========================================================================
|
||||
// API Version 1
|
||||
|
||||
v1Base := v1.BaseUrlFunc(prefix)
|
||||
v1Ctrl := v1.NewControllerV1(a.services)
|
||||
{
|
||||
v1Handlers := v1.NewControllerV1(a.services)
|
||||
r.Post(v1Base("/users/register"), v1Handlers.HandleUserRegistration())
|
||||
r.Post(v1Base("/users/login"), v1Handlers.HandleAuthLogin())
|
||||
r.Get(v1Base("/status"), v1Ctrl.HandleBase(func() bool { return true }, "v1"))
|
||||
|
||||
r.Post(v1Base("/users/register"), v1Ctrl.HandleUserRegistration())
|
||||
r.Post(v1Base("/users/login"), v1Ctrl.HandleAuthLogin())
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(a.mwAuthToken)
|
||||
r.Get(v1Base("/users/self"), v1Handlers.HandleUserSelf())
|
||||
r.Put(v1Base("/users/self"), v1Handlers.HandleUserUpdate())
|
||||
r.Put(v1Base("/users/self/password"), v1Handlers.HandleUserUpdatePassword())
|
||||
r.Post(v1Base("/users/logout"), v1Handlers.HandleAuthLogout())
|
||||
r.Get(v1Base("/users/refresh"), v1Handlers.HandleAuthRefresh())
|
||||
r.Get(v1Base("/users/self"), v1Ctrl.HandleUserSelf())
|
||||
r.Put(v1Base("/users/self"), v1Ctrl.HandleUserSelfUpdate())
|
||||
r.Delete(v1Base("/users/self"), v1Ctrl.HandleUserSelfDelete())
|
||||
r.Put(v1Base("/users/self/password"), v1Ctrl.HandleUserUpdatePassword())
|
||||
r.Post(v1Base("/users/logout"), v1Ctrl.HandleAuthLogout())
|
||||
r.Get(v1Base("/users/refresh"), v1Ctrl.HandleAuthRefresh())
|
||||
|
||||
r.Get(v1Base("/locations"), v1Handlers.HandleLocationGetAll())
|
||||
r.Post(v1Base("/locations"), v1Handlers.HandleLocationCreate())
|
||||
r.Get(v1Base("/locations/{id}"), v1Handlers.HandleLocationGet())
|
||||
r.Put(v1Base("/locations/{id}"), v1Handlers.HandleLocationUpdate())
|
||||
r.Delete(v1Base("/locations/{id}"), v1Handlers.HandleLocationDelete())
|
||||
r.Get(v1Base("/locations"), v1Ctrl.HandleLocationGetAll())
|
||||
r.Post(v1Base("/locations"), v1Ctrl.HandleLocationCreate())
|
||||
r.Get(v1Base("/locations/{id}"), v1Ctrl.HandleLocationGet())
|
||||
r.Put(v1Base("/locations/{id}"), v1Ctrl.HandleLocationUpdate())
|
||||
r.Delete(v1Base("/locations/{id}"), v1Ctrl.HandleLocationDelete())
|
||||
|
||||
r.Get(v1Base("/labels"), v1Handlers.HandleLabelsGetAll())
|
||||
r.Post(v1Base("/labels"), v1Handlers.HandleLabelsCreate())
|
||||
r.Get(v1Base("/labels/{id}"), v1Handlers.HandleLabelGet())
|
||||
r.Put(v1Base("/labels/{id}"), v1Handlers.HandleLabelUpdate())
|
||||
r.Delete(v1Base("/labels/{id}"), v1Handlers.HandleLabelDelete())
|
||||
r.Get(v1Base("/labels"), v1Ctrl.HandleLabelsGetAll())
|
||||
r.Post(v1Base("/labels"), v1Ctrl.HandleLabelsCreate())
|
||||
r.Get(v1Base("/labels/{id}"), v1Ctrl.HandleLabelGet())
|
||||
r.Put(v1Base("/labels/{id}"), v1Ctrl.HandleLabelUpdate())
|
||||
r.Delete(v1Base("/labels/{id}"), v1Ctrl.HandleLabelDelete())
|
||||
|
||||
r.Get(v1Base("/items"), v1Handlers.HandleItemsGetAll())
|
||||
r.Post(v1Base("/items"), v1Handlers.HandleItemsCreate())
|
||||
r.Get(v1Base("/items/{id}"), v1Handlers.HandleItemGet())
|
||||
r.Put(v1Base("/items/{id}"), v1Handlers.HandleItemUpdate())
|
||||
r.Delete(v1Base("/items/{id}"), v1Handlers.HandleItemDelete())
|
||||
r.Get(v1Base("/items"), v1Ctrl.HandleItemsGetAll())
|
||||
r.Post(v1Base("/items"), v1Ctrl.HandleItemsCreate())
|
||||
r.Get(v1Base("/items/{id}"), v1Ctrl.HandleItemGet())
|
||||
r.Put(v1Base("/items/{id}"), v1Ctrl.HandleItemUpdate())
|
||||
r.Delete(v1Base("/items/{id}"), v1Ctrl.HandleItemDelete())
|
||||
})
|
||||
}
|
||||
|
||||
r.NotFound(NotFoundHandler)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
|
@ -78,7 +88,7 @@ func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux {
|
|||
func (a *app) LogRoutes(r *chi.Mux) {
|
||||
desiredSpaces := 10
|
||||
|
||||
walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
|
||||
walkFunc := func(method string, route string, handler http.Handler, middleware ...func(http.Handler) http.Handler) error {
|
||||
text := "[" + method + "]"
|
||||
|
||||
for len(text) < desiredSpaces {
|
||||
|
@ -93,3 +103,56 @@ func (a *app) LogRoutes(r *chi.Mux) {
|
|||
fmt.Printf("Logging err: %s\n", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
var ErrDir = errors.New("path is dir")
|
||||
|
||||
func init() {
|
||||
mime.AddExtensionType(".js", "application/javascript")
|
||||
mime.AddExtensionType(".mjs", "application/javascript")
|
||||
}
|
||||
|
||||
func tryRead(fs embed.FS, prefix, requestedPath string, w http.ResponseWriter) error {
|
||||
f, err := fs.Open(path.Join(prefix, requestedPath))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
stat, _ := f.Stat()
|
||||
if stat.IsDir() {
|
||||
return ErrDir
|
||||
}
|
||||
|
||||
contentType := mime.TypeByExtension(filepath.Ext(requestedPath))
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
_, err = io.Copy(w, f)
|
||||
return err
|
||||
}
|
||||
|
||||
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
|
||||
err := tryRead(public, "public", r.URL.Path, w)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
log.Debug().
|
||||
Str("path", r.URL.Path).
|
||||
Msg("served from embed not found - serving index.html")
|
||||
err = tryRead(public, "public", "index.html", w)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func DumpEmbedContents() {
|
||||
// recursively prints all contents in the embed.FS
|
||||
err := fs.WalkDir(public, ".", func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(path)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/content/backend/ent"
|
||||
"github.com/hay-kot/content/backend/internal/repo"
|
||||
"github.com/hay-kot/content/backend/internal/types"
|
||||
"github.com/hay-kot/content/backend/pkgs/hasher"
|
||||
|
@ -60,25 +61,28 @@ func (a *app) SeedDatabase(repos *repo.AllRepos) {
|
|||
log.Fatal().Err(err).Msg("failed to create default group")
|
||||
}
|
||||
|
||||
for _, user := range a.conf.Seed.Users {
|
||||
for _, seedUser := range a.conf.Seed.Users {
|
||||
|
||||
// Check if User Exists
|
||||
usr, _ := repos.Users.GetOneEmail(context.Background(), user.Email)
|
||||
usr, err := repos.Users.GetOneEmail(context.Background(), seedUser.Email)
|
||||
if err != nil && !ent.IsNotFound(err) {
|
||||
log.Fatal().Err(err).Msg("failed to get user")
|
||||
}
|
||||
|
||||
if usr.ID != uuid.Nil {
|
||||
log.Info().Str("email", user.Email).Msg("user already exists, skipping")
|
||||
if usr != nil && usr.ID != uuid.Nil {
|
||||
log.Info().Str("email", seedUser.Email).Msg("user already exists, skipping")
|
||||
continue
|
||||
}
|
||||
|
||||
hashedPw, err := hasher.HashPassword(user.Password)
|
||||
hashedPw, err := hasher.HashPassword(seedUser.Password)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("failed to hash password")
|
||||
}
|
||||
|
||||
_, err = repos.Users.Create(context.Background(), types.UserCreate{
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
IsSuperuser: user.IsSuperuser,
|
||||
Name: seedUser.Name,
|
||||
Email: seedUser.Email,
|
||||
IsSuperuser: seedUser.IsSuperuser,
|
||||
Password: hashedPw,
|
||||
GroupID: group.ID,
|
||||
})
|
||||
|
@ -87,6 +91,6 @@ func (a *app) SeedDatabase(repos *repo.AllRepos) {
|
|||
log.Fatal().Err(err).Msg("failed to create user")
|
||||
}
|
||||
|
||||
log.Info().Str("email", user.Email).Msg("created user")
|
||||
log.Info().Str("email", seedUser.Email).Msg("created user")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,11 @@
|
|||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/content/backend/internal/services"
|
||||
"github.com/hay-kot/content/backend/internal/types"
|
||||
"github.com/hay-kot/content/backend/pkgs/server"
|
||||
)
|
||||
|
||||
type V1Controller struct {
|
||||
|
@ -24,3 +28,22 @@ func NewControllerV1(svc *services.AllServices) *V1Controller {
|
|||
|
||||
return ctrl
|
||||
}
|
||||
|
||||
type ReadyFunc func() bool
|
||||
|
||||
// HandleBase godoc
|
||||
// @Summary Retrieves the basic information about the API
|
||||
// @Tags Base
|
||||
// @Produce json
|
||||
// @Success 200 {object} types.ApiSummary
|
||||
// @Router /v1/status [GET]
|
||||
func (ctrl *V1Controller) HandleBase(ready ReadyFunc, versions ...string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
server.Respond(w, http.StatusOK, types.ApiSummary{
|
||||
Healthy: ready(),
|
||||
Versions: versions,
|
||||
Title: "Go API Template",
|
||||
Message: "Welcome to the Go API Template Application!",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
@ -16,3 +18,25 @@ func Test_NewHandlerV1(t *testing.T) {
|
|||
assert.Equal(t, "/testing/v1/v1/abc123", v1Base("/abc123"))
|
||||
assert.Equal(t, "/testing/v1/v1/abc123", v1Base("/abc123"))
|
||||
}
|
||||
|
||||
func TestHandlersv1_HandleBase(t *testing.T) {
|
||||
// Setup
|
||||
hdlrFunc := mockHandler.HandleBase(func() bool { return true }, "v1")
|
||||
|
||||
// Call Handler Func
|
||||
rr := httptest.NewRecorder()
|
||||
hdlrFunc(rr, nil)
|
||||
|
||||
// Validate Status Code
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("Expected status code to be %d, got %d", http.StatusOK, rr.Code)
|
||||
}
|
||||
|
||||
// Validate Json Payload
|
||||
expected := `{"health":true,"versions":["v1"],"title":"Go API Template","message":"Welcome to the Go API Template Application!"}`
|
||||
|
||||
if rr.Body.String() != expected {
|
||||
t.Errorf("Expected json to be %s, got %s", expected, rr.Body.String())
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -58,7 +58,7 @@ func (ctrl *V1Controller) HandleUserSelf() http.HandlerFunc {
|
|||
}
|
||||
}
|
||||
|
||||
// HandleUserUpdate godoc
|
||||
// HandleUserSelfUpdate godoc
|
||||
// @Summary Update the current user
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
|
@ -66,7 +66,7 @@ func (ctrl *V1Controller) HandleUserSelf() http.HandlerFunc {
|
|||
// @Success 200 {object} server.Result{item=types.UserUpdate}
|
||||
// @Router /v1/users/self [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserUpdate() http.HandlerFunc {
|
||||
func (ctrl *V1Controller) HandleUserSelfUpdate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateData := types.UserUpdate{}
|
||||
if err := server.Decode(r, &updateData); err != nil {
|
||||
|
@ -99,3 +99,22 @@ func (ctrl *V1Controller) HandleUserUpdatePassword() http.HandlerFunc {
|
|||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUserSelfDelete godoc
|
||||
// @Summary Deletes the user account
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Success 204
|
||||
// @Router /v1/users/self [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserSelfDelete() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
actor := services.UseUserCtx(r.Context())
|
||||
if err := ctrl.svc.User.DeleteSelf(r.Context(), actor.ID); err != nil {
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,8 +4,8 @@ swagger:
|
|||
host: localhost:7745
|
||||
scheme: http
|
||||
web:
|
||||
port: 3915
|
||||
host: 127.0.0.1
|
||||
port: 7745
|
||||
host:
|
||||
database:
|
||||
driver: sqlite3
|
||||
sqlite-url: ./ent.db?_fk=1
|
||||
|
|
|
@ -1,10 +0,0 @@
|
|||
version: "3.4"
|
||||
|
||||
services:
|
||||
gowebtemplate:
|
||||
image: gowebtemplate
|
||||
build:
|
||||
context: .
|
||||
dockerfile: ./Dockerfile
|
||||
ports:
|
||||
- 3001:7745
|
|
@ -2,6 +2,7 @@ package schema
|
|||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/hay-kot/content/backend/ent/schema/mixins"
|
||||
|
@ -33,9 +34,17 @@ func (Group) Fields() []ent.Field {
|
|||
// Edges of the Home.
|
||||
func (Group) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("users", User.Type),
|
||||
edge.To("locations", Location.Type),
|
||||
edge.To("items", Item.Type),
|
||||
edge.To("labels", Label.Type),
|
||||
edge.To("users", User.Type).Annotations(entsql.Annotation{
|
||||
OnDelete: entsql.Cascade,
|
||||
}),
|
||||
edge.To("locations", Location.Type).Annotations(entsql.Annotation{
|
||||
OnDelete: entsql.Cascade,
|
||||
}),
|
||||
edge.To("items", Item.Type).Annotations(entsql.Annotation{
|
||||
OnDelete: entsql.Cascade,
|
||||
}),
|
||||
edge.To("labels", Label.Type).Annotations(entsql.Annotation{
|
||||
OnDelete: entsql.Cascade,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ package schema
|
|||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
|
@ -73,7 +74,9 @@ func (Item) Edges() []ent.Edge {
|
|||
edge.From("location", Location.Type).
|
||||
Ref("items").
|
||||
Unique(),
|
||||
edge.To("fields", ItemField.Type),
|
||||
edge.To("fields", ItemField.Type).Annotations(entsql.Annotation{
|
||||
OnDelete: entsql.Cascade,
|
||||
}),
|
||||
edge.From("label", Label.Type).
|
||||
Ref("items"),
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ package schema
|
|||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/hay-kot/content/backend/ent/schema/mixins"
|
||||
|
@ -44,6 +45,8 @@ func (User) Edges() []ent.Edge {
|
|||
Ref("users").
|
||||
Required().
|
||||
Unique(),
|
||||
edge.To("auth_tokens", AuthTokens.Type),
|
||||
edge.To("auth_tokens", AuthTokens.Type).Annotations(entsql.Annotation{
|
||||
OnDelete: entsql.Cascade,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,7 +33,7 @@ type SwaggerConf struct {
|
|||
|
||||
type WebConfig struct {
|
||||
Port string `yaml:"port" conf:"default:7745"`
|
||||
Host string `yaml:"host" conf:"default:127.0.0.1"`
|
||||
Host string `yaml:"host"`
|
||||
}
|
||||
|
||||
// NewConfig parses the CLI/Config file and returns a Config struct. If the file argument is an empty string, the
|
||||
|
|
|
@ -14,23 +14,17 @@ type EntUserRepository struct {
|
|||
}
|
||||
|
||||
func (e *EntUserRepository) GetOneId(ctx context.Context, id uuid.UUID) (*ent.User, error) {
|
||||
usr, err := e.db.User.Query().Where(user.ID(id)).Only(ctx)
|
||||
|
||||
if err != nil {
|
||||
return usr, err
|
||||
}
|
||||
|
||||
return usr, nil
|
||||
return e.db.User.Query().
|
||||
Where(user.ID(id)).
|
||||
WithGroup().
|
||||
Only(ctx)
|
||||
}
|
||||
|
||||
func (e *EntUserRepository) GetOneEmail(ctx context.Context, email string) (*ent.User, error) {
|
||||
usr, err := e.db.User.Query().Where(user.Email(email)).Only(ctx)
|
||||
|
||||
if err != nil {
|
||||
return usr, err
|
||||
}
|
||||
|
||||
return usr, nil
|
||||
return e.db.User.Query().
|
||||
Where(user.Email(email)).
|
||||
WithGroup().
|
||||
Only(ctx)
|
||||
}
|
||||
|
||||
func (e *EntUserRepository) GetAll(ctx context.Context) ([]*ent.User, error) {
|
||||
|
@ -59,7 +53,11 @@ func (e *EntUserRepository) Create(ctx context.Context, usr types.UserCreate) (*
|
|||
SetGroupID(usr.GroupID).
|
||||
Save(ctx)
|
||||
|
||||
return entUser, err
|
||||
if err != nil {
|
||||
return entUser, err
|
||||
}
|
||||
|
||||
return e.GetOneId(ctx, entUser.ID)
|
||||
}
|
||||
|
||||
func (e *EntUserRepository) Update(ctx context.Context, ID uuid.UUID, data types.UserUpdate) error {
|
||||
|
|
20
backend/internal/services/mappers/user.go
Normal file
20
backend/internal/services/mappers/user.go
Normal file
|
@ -0,0 +1,20 @@
|
|||
package mappers
|
||||
|
||||
import (
|
||||
"github.com/hay-kot/content/backend/ent"
|
||||
"github.com/hay-kot/content/backend/internal/types"
|
||||
)
|
||||
|
||||
func ToOutUser(user *ent.User, err error) (*types.UserOut, error) {
|
||||
if err != nil {
|
||||
return &types.UserOut{}, err
|
||||
}
|
||||
return &types.UserOut{
|
||||
ID: user.ID,
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
IsSuperuser: user.IsSuperuser,
|
||||
GroupName: user.Edges.Group.Name,
|
||||
GroupID: user.Edges.Group.ID,
|
||||
}, nil
|
||||
}
|
|
@ -6,8 +6,8 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/content/backend/ent"
|
||||
"github.com/hay-kot/content/backend/internal/repo"
|
||||
"github.com/hay-kot/content/backend/internal/services/mappers"
|
||||
"github.com/hay-kot/content/backend/internal/types"
|
||||
"github.com/hay-kot/content/backend/pkgs/hasher"
|
||||
)
|
||||
|
@ -23,24 +23,6 @@ type UserService struct {
|
|||
repos *repo.AllRepos
|
||||
}
|
||||
|
||||
func ToOutUser(user *ent.User, err error) (*types.UserOut, error) {
|
||||
if err != nil {
|
||||
return &types.UserOut{}, err
|
||||
}
|
||||
return &types.UserOut{
|
||||
ID: user.ID,
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
IsSuperuser: user.IsSuperuser,
|
||||
GroupName: user.Edges.Group.Name,
|
||||
GroupID: user.Edges.Group.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (UserService) toOutUser(user *ent.User, err error) (*types.UserOut, error) {
|
||||
return ToOutUser(user, err)
|
||||
}
|
||||
|
||||
func (svc *UserService) RegisterUser(ctx context.Context, data types.UserRegistration) (*types.UserOut, error) {
|
||||
group, err := svc.repos.Groups.Create(ctx, data.GroupName)
|
||||
if err != nil {
|
||||
|
@ -48,7 +30,6 @@ func (svc *UserService) RegisterUser(ctx context.Context, data types.UserRegistr
|
|||
}
|
||||
|
||||
hashed, _ := hasher.HashPassword(data.User.Password)
|
||||
|
||||
usrCreate := types.UserCreate{
|
||||
Name: data.User.Name,
|
||||
Email: data.User.Email,
|
||||
|
@ -57,23 +38,22 @@ func (svc *UserService) RegisterUser(ctx context.Context, data types.UserRegistr
|
|||
GroupID: group.ID,
|
||||
}
|
||||
|
||||
return svc.toOutUser(svc.repos.Users.Create(ctx, usrCreate))
|
||||
return mappers.ToOutUser(svc.repos.Users.Create(ctx, usrCreate))
|
||||
}
|
||||
|
||||
// GetSelf returns the user that is currently logged in based of the token provided within
|
||||
func (svc *UserService) GetSelf(ctx context.Context, requestToken string) (*types.UserOut, error) {
|
||||
hash := hasher.HashToken(requestToken)
|
||||
return svc.toOutUser(svc.repos.AuthTokens.GetUserFromToken(ctx, hash))
|
||||
return mappers.ToOutUser(svc.repos.AuthTokens.GetUserFromToken(ctx, hash))
|
||||
}
|
||||
|
||||
func (svc *UserService) UpdateSelf(ctx context.Context, ID uuid.UUID, data types.UserUpdate) (*types.UserOut, error) {
|
||||
err := svc.repos.Users.Update(ctx, ID, data)
|
||||
|
||||
if err != nil {
|
||||
return &types.UserOut{}, err
|
||||
}
|
||||
|
||||
return svc.toOutUser(svc.repos.Users.GetOneId(ctx, ID))
|
||||
return mappers.ToOutUser(svc.repos.Users.GetOneId(ctx, ID))
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
|
@ -120,3 +100,10 @@ func (svc *UserService) RenewToken(ctx context.Context, token string) (types.Use
|
|||
|
||||
return newToken, nil
|
||||
}
|
||||
|
||||
// DeleteSelf deletes the user that is currently logged based of the provided UUID
|
||||
// There is _NO_ protection against deleting the wrong user, as such this should only
|
||||
// be used when the identify of the user has been confirmed.
|
||||
func (svc *UserService) DeleteSelf(ctx context.Context, ID uuid.UUID) error {
|
||||
return svc.repos.Users.Delete(ctx, ID)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue