Compare commits
No commits in common. "20ef75b1aaec68d1e3858c333578ea3044888cc8" and "544ccbe1ca882aebaf402dc76e0a770b4fff3d2a" have entirely different histories.
20ef75b1aa
...
544ccbe1ca
2
.gitignore
vendored
2
.gitignore
vendored
@ -24,7 +24,7 @@ go.work.sum
|
||||
|
||||
# Custom
|
||||
/_output
|
||||
/deployment/tmp
|
||||
/deployment/db_data
|
||||
/tmp/**
|
||||
|
||||
# Vue
|
||||
|
2
Makefile
2
Makefile
@ -34,7 +34,7 @@ web: web-all
|
||||
|
||||
.PHONY: build
|
||||
build: tidy sqlc # build.
|
||||
@go build -v -ldflags "$(GO_LDFLAGS)" -o $(OUTPUT_DIR)/howmuch $(ROOT_DIR)/cmd/howmuch/main.go
|
||||
@go build -v -ldflags "$(GO_LDFLAGS)" -o $(OUTPUT_DIR)/howmuch $(ROOT_DIR)/cmd/howmuch/main.go 2>/dev/null
|
||||
|
||||
.PHONY: sqlc
|
||||
sqlc:
|
||||
|
@ -76,6 +76,7 @@ paths:
|
||||
/session/create:
|
||||
post:
|
||||
tags:
|
||||
- user
|
||||
- session
|
||||
description: Create a new session for a user
|
||||
requestBody:
|
||||
@ -84,41 +85,6 @@ paths:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/SessionCreateRequest'
|
||||
responses:
|
||||
'200':
|
||||
description: Successful operation
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
token:
|
||||
type: string
|
||||
example: fakjshdflauhkjhsometokenakjsdhfaksj
|
||||
'400':
|
||||
description: Client side error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
example: AuthFailure
|
||||
message:
|
||||
type: string
|
||||
example: "wrong email password."
|
||||
'500':
|
||||
description: Server side error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrResponse'
|
||||
/session/delete:
|
||||
post:
|
||||
tags:
|
||||
- session
|
||||
description: Delete an existing session for a user
|
||||
responses:
|
||||
'200':
|
||||
description: Successful operation
|
||||
@ -144,15 +110,13 @@ paths:
|
||||
example: AuthFailure
|
||||
message:
|
||||
type: string
|
||||
example: "user not logged in."
|
||||
example: "wrong email password."
|
||||
'500':
|
||||
description: Server side error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrResponse'
|
||||
security:
|
||||
- jwt: []
|
||||
|
||||
components:
|
||||
schemas:
|
||||
@ -197,9 +161,3 @@ components:
|
||||
message:
|
||||
type: string
|
||||
example: "Server internal error."
|
||||
securitySchemes:
|
||||
jwt:
|
||||
name: Bearer authentication
|
||||
type: http
|
||||
bearerFormat: "JWT"
|
||||
scheme: bearer
|
||||
|
@ -16,14 +16,6 @@ db:
|
||||
# DB name
|
||||
database: howmuch
|
||||
|
||||
max-open-conns: 100
|
||||
max-idle-conns: 100
|
||||
max-lifetime: 10s
|
||||
|
||||
cache:
|
||||
host: 127.0.0.1:6379
|
||||
password: ""
|
||||
|
||||
log:
|
||||
level: debug
|
||||
disalbe-caller: false
|
||||
|
5
go.mod
5
go.mod
@ -11,7 +11,6 @@ require (
|
||||
github.com/gosuri/uitable v0.0.4
|
||||
github.com/jackc/pgx/v5 v5.7.1
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/redis/go-redis/v9 v9.6.1
|
||||
github.com/spf13/cobra v1.8.1
|
||||
github.com/spf13/pflag v1.0.5
|
||||
github.com/spf13/viper v1.19.0
|
||||
@ -24,11 +23,9 @@ require (
|
||||
require (
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/fatih/color v1.14.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
@ -41,7 +38,6 @@ require (
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
@ -66,7 +62,6 @@ require (
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
|
||||
golang.org/x/sync v0.8.0 // indirect
|
||||
golang.org/x/sys v0.25.0 // indirect
|
||||
golang.org/x/text v0.18.0 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
|
10
go.sum
10
go.sum
@ -1,13 +1,7 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
@ -17,8 +11,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w=
|
||||
github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
@ -99,8 +91,6 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.6.1 h1:HHDteefn6ZkTtY5fGUE8tj8uy85AHk6zP7CpzIAM0y4=
|
||||
github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
|
@ -23,31 +23,25 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/model"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/usecase/usecase"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/middleware/authn"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/token"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Session interface {
|
||||
Create(*gin.Context)
|
||||
Delete(*gin.Context)
|
||||
}
|
||||
|
||||
type SessionController struct {
|
||||
userUsecase usecase.User
|
||||
cache core.Cache
|
||||
}
|
||||
|
||||
func NewSessionController(u usecase.User, cache core.Cache) Session {
|
||||
return &SessionController{u, cache}
|
||||
func NewSessionController(u usecase.User) Session {
|
||||
return &SessionController{u}
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
@ -94,27 +88,3 @@ func (sc *SessionController) Create(ctx *gin.Context) {
|
||||
Token: tokenString,
|
||||
})
|
||||
}
|
||||
|
||||
// Delete deletes a session by putting the jwt token into the cache
|
||||
func (sc *SessionController) Delete(ctx *gin.Context) {
|
||||
tk, err := token.ParseRequest(ctx)
|
||||
if err != nil || tk == nil {
|
||||
// Unlikely
|
||||
core.WriteResponse(ctx, authn.ErrTokenInvalid, nil)
|
||||
return
|
||||
}
|
||||
|
||||
exp := time.Until(tk.Expiry)
|
||||
key := fmt.Sprintf("jwt:%s", tk.Identity)
|
||||
|
||||
log.DebugLog("session delete", "key", key, "exp", exp.String())
|
||||
err = sc.cache.Set(ctx, key, tk.Raw, exp)
|
||||
if err != nil {
|
||||
// unexpected
|
||||
log.ErrorLog("error writing logged out jwt into cache", "err", err)
|
||||
core.WriteResponse(ctx, errno.InternalServerErr, nil)
|
||||
return
|
||||
}
|
||||
|
||||
core.WriteResponse(ctx, nil, "logged out")
|
||||
}
|
||||
|
@ -59,7 +59,7 @@ func TestSessionCreate(t *testing.T) {
|
||||
for _, tst := range tests {
|
||||
t.Run(tst.Name, func(t *testing.T) {
|
||||
testUserUsecase := usecasemock.NewtestUserUsecase()
|
||||
sessionController := NewSessionController(testUserUsecase, nil)
|
||||
sessionController := NewSessionController(testUserUsecase)
|
||||
r := gin.New()
|
||||
r.POST(
|
||||
"/session/create",
|
||||
|
@ -24,17 +24,17 @@ package repo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/usecase/repo"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type dbRepository struct {
|
||||
db *sql.DB
|
||||
db *pgx.Conn
|
||||
}
|
||||
|
||||
func NewDBRepository(db *sql.DB) repo.DBRepository {
|
||||
func NewDBRepository(db *pgx.Conn) repo.DBRepository {
|
||||
return &dbRepository{
|
||||
db: db,
|
||||
}
|
||||
@ -46,20 +46,20 @@ func (dr *dbRepository) Transaction(
|
||||
ctx context.Context,
|
||||
txFunc func(txCtx context.Context, tx interface{}) (interface{}, error),
|
||||
) (interface{}, error) {
|
||||
tx, err := dr.db.BeginTx(ctx, nil)
|
||||
tx, err := dr.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
tx.Rollback()
|
||||
tx.Rollback(ctx)
|
||||
log.PanicLog("transaction panicked!")
|
||||
} else if err != nil {
|
||||
tx.Rollback()
|
||||
tx.Rollback(ctx)
|
||||
log.ErrorLog("transaction failed!", "err", err)
|
||||
} else {
|
||||
err = tx.Commit()
|
||||
err = tx.Commit(ctx)
|
||||
}
|
||||
}()
|
||||
|
||||
|
@ -6,14 +6,15 @@ package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
|
||||
PrepareContext(context.Context, string) (*sql.Stmt, error)
|
||||
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
|
||||
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
@ -24,7 +25,7 @@ type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx *sql.Tx) *Queries {
|
||||
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
|
@ -5,7 +5,7 @@
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"time"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type Admin struct {
|
||||
@ -21,6 +21,6 @@ type User struct {
|
||||
FirstName string
|
||||
LastName string
|
||||
Password string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CreatedAt pgtype.Timestamp
|
||||
UpdatedAt pgtype.Timestamp
|
||||
}
|
||||
|
@ -7,7 +7,8 @@ package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getUserByEmail = `-- name: GetUserByEmail :one
|
||||
@ -17,7 +18,7 @@ SELECT id, email, first_name, last_name, password, created_at, updated_at
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) {
|
||||
row := q.db.QueryRowContext(ctx, getUserByEmail, email)
|
||||
row := q.db.QueryRow(ctx, getUserByEmail, email)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
@ -44,8 +45,8 @@ type InsertUserParams struct {
|
||||
FirstName string
|
||||
LastName string
|
||||
Password string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CreatedAt pgtype.Timestamp
|
||||
UpdatedAt pgtype.Timestamp
|
||||
}
|
||||
|
||||
// MIT License
|
||||
@ -70,7 +71,7 @@ type InsertUserParams struct {
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) (User, error) {
|
||||
row := q.db.QueryRowContext(ctx, insertUser,
|
||||
row := q.db.QueryRow(ctx, insertUser,
|
||||
arg.Email,
|
||||
arg.FirstName,
|
||||
arg.LastName,
|
||||
|
@ -24,7 +24,6 @@ package repo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
@ -32,15 +31,16 @@ import (
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/model"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/usecase/repo"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type userRepository struct {
|
||||
db *sql.DB
|
||||
db *pgx.Conn
|
||||
}
|
||||
|
||||
const insertTimeout = 1 * time.Second
|
||||
|
||||
func NewUserRepository(db *sql.DB) repo.UserRepository {
|
||||
func NewUserRepository(db *pgx.Conn) repo.UserRepository {
|
||||
return &userRepository{
|
||||
db: db,
|
||||
}
|
||||
@ -60,11 +60,11 @@ func (ur *userRepository) Create(
|
||||
FirstName: u.FirstName,
|
||||
LastName: u.LastName,
|
||||
Password: u.Password,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
CreatedAt: pgtype.Timestamp{Time: time.Now(), Valid: true},
|
||||
UpdatedAt: pgtype.Timestamp{Time: time.Now(), Valid: true},
|
||||
}
|
||||
|
||||
tx, ok := transaction.(*sql.Tx)
|
||||
tx, ok := transaction.(pgx.Tx)
|
||||
if !ok {
|
||||
return nil, errors.New("transaction is not a pgx.Tx")
|
||||
}
|
||||
@ -82,8 +82,8 @@ func (ur *userRepository) Create(
|
||||
FirstName: userDB.FirstName,
|
||||
LastName: userDB.LastName,
|
||||
Password: userDB.Password,
|
||||
CreatedAt: userDB.CreatedAt,
|
||||
UpdatedAt: userDB.CreatedAt,
|
||||
CreatedAt: userDB.CreatedAt.Time,
|
||||
UpdatedAt: userDB.CreatedAt.Time,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@ -104,7 +104,7 @@ func (ur *userRepository) GetByEmail(ctx context.Context, email string) (*model.
|
||||
FirstName: userDB.FirstName,
|
||||
LastName: userDB.LastName,
|
||||
Password: userDB.Password,
|
||||
CreatedAt: userDB.CreatedAt,
|
||||
UpdatedAt: userDB.CreatedAt,
|
||||
CreatedAt: userDB.CreatedAt.Time,
|
||||
UpdatedAt: userDB.CreatedAt.Time,
|
||||
}, nil
|
||||
}
|
||||
|
@ -38,7 +38,7 @@ import (
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/token"
|
||||
"git.vinchent.xyz/vinchent/howmuch/pkg/version/verflag"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"golang.org/x/net/context"
|
||||
@ -116,35 +116,25 @@ func run() error {
|
||||
viper.GetString("db.password"),
|
||||
viper.GetString("db.sslmode"),
|
||||
)
|
||||
// TODO: viper conf should be parsed into a struct directly
|
||||
dbExtraConf := &datastore.DbExtraConf{
|
||||
MaxOpenConns: viper.GetInt("db.max-open-conns"),
|
||||
MaxIdleConns: viper.GetInt("db.max-idle-conns"),
|
||||
MaxLifetime: viper.GetDuration("db.max-lifetime"),
|
||||
dbConf, err := pgx.ParseConfig(dbConfString)
|
||||
if err != nil {
|
||||
log.FatalLog("DB connection config failure", "err", err, "cfg string", dbConfString)
|
||||
}
|
||||
dbConn := datastore.NewDB(dbConfString, dbExtraConf)
|
||||
if dbConn == nil {
|
||||
log.FatalLog("DB connection failure")
|
||||
dbConn, err := datastore.NewDB(dbConf)
|
||||
if err != nil {
|
||||
log.FatalLog("DB connection failure", "err", err)
|
||||
}
|
||||
defer dbConn.Close()
|
||||
|
||||
// Init Cache
|
||||
cache := datastore.NewCache(&redis.Options{
|
||||
Addr: viper.GetString("cache.host"),
|
||||
Password: viper.GetString("cache.password"),
|
||||
DB: 0,
|
||||
})
|
||||
defer cache.Close()
|
||||
defer dbConn.Close(context.Background())
|
||||
|
||||
// Init token
|
||||
token.Init(viper.GetString("web.token-secret"), viper.GetDuration("web.token-expiry-time"))
|
||||
|
||||
// Register the core service
|
||||
r := registry.NewRegistry(dbConn, cache)
|
||||
r := registry.NewRegistry(dbConn)
|
||||
|
||||
engine := gin.Default()
|
||||
|
||||
engine = router.Routes(engine, r.NewAppController(), cache)
|
||||
engine = router.Routes(engine, r.NewAppController())
|
||||
|
||||
server := http.Server{
|
||||
Addr: viper.GetString("web.addr"),
|
||||
|
@ -1,66 +0,0 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package datastore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type RedisCache struct {
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
func NewCache(opt interface{}) core.Cache {
|
||||
redisOpt := opt.(*redis.Options)
|
||||
return &RedisCache{redis.NewClient(redisOpt)}
|
||||
}
|
||||
|
||||
func (c *RedisCache) Get(ctx context.Context, key string) (string, error) {
|
||||
val, err := c.redis.Get(ctx, key).Result()
|
||||
if err == redis.Nil {
|
||||
log.DebugLog("redis key not found", "key", key)
|
||||
return "", nil
|
||||
} else if err != nil {
|
||||
log.DebugLog("redis cache get error", "err", err)
|
||||
return "", err
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
|
||||
func (c *RedisCache) Set(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
value interface{},
|
||||
expiration time.Duration,
|
||||
) error {
|
||||
return c.redis.Set(ctx, key, value, expiration).Err()
|
||||
}
|
||||
|
||||
func (c *RedisCache) Close() error {
|
||||
return c.redis.Close()
|
||||
}
|
@ -23,65 +23,22 @@
|
||||
package datastore
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
"context"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
|
||||
_ "github.com/jackc/pgx/v5"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
var counts int
|
||||
|
||||
type DbExtraConf struct {
|
||||
MaxOpenConns int
|
||||
MaxIdleConns int
|
||||
MaxLifetime time.Duration
|
||||
}
|
||||
|
||||
// NewDB creates a new database for the application
|
||||
func NewDB(dsn string, opts interface{}) *sql.DB {
|
||||
var db *sql.DB
|
||||
var err error
|
||||
|
||||
for {
|
||||
db, err = openDB(dsn)
|
||||
if err != nil {
|
||||
log.WarnLog("postgres not ready", "err", err)
|
||||
counts++
|
||||
} else {
|
||||
log.InfoLog("connected to postgres")
|
||||
break
|
||||
}
|
||||
|
||||
if counts > 10 {
|
||||
break
|
||||
}
|
||||
log.InfoLog("retry in 2 seconds")
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
extraConf, ok := opts.(DbExtraConf)
|
||||
if ok {
|
||||
db.SetMaxOpenConns(extraConf.MaxOpenConns)
|
||||
db.SetMaxIdleConns(extraConf.MaxIdleConns)
|
||||
db.SetConnMaxLifetime(extraConf.MaxLifetime)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func openDB(dsn string) (*sql.DB, error) {
|
||||
db, err := sql.Open("pgx", dsn)
|
||||
func NewDB(connConfig *pgx.ConnConfig) (*pgx.Conn, error) {
|
||||
conn, err := pgx.ConnectConfig(context.Background(), connConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := db.Ping(); err != nil {
|
||||
// Ping test the conn
|
||||
if err = conn.Ping(context.Background()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
|
||||
return conn, err
|
||||
}
|
||||
|
@ -29,19 +29,11 @@ import (
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/middleware"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/middleware/authn"
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Routes can take some options to init middlewares.
|
||||
// - Cache
|
||||
func Routes(engine *gin.Engine, c controller.AppController, opt ...interface{}) *gin.Engine {
|
||||
cache, ok := opt[0].(core.Cache)
|
||||
if !ok {
|
||||
panic("the first option must be a cache driver")
|
||||
}
|
||||
|
||||
func Routes(engine *gin.Engine, c controller.AppController) *gin.Engine {
|
||||
// Middlewares
|
||||
// Cors
|
||||
corsCfg := cors.DefaultConfig()
|
||||
@ -64,20 +56,14 @@ func Routes(engine *gin.Engine, c controller.AppController, opt ...interface{})
|
||||
{
|
||||
userV1.POST("/create", func(ctx *gin.Context) { c.User.Create(ctx) })
|
||||
|
||||
userV1.Use(authn.Authn(cache))
|
||||
userV1.Use(middleware.Authn())
|
||||
userV1.GET(
|
||||
":id/info",
|
||||
func(ctx *gin.Context) { ctx.JSON(http.StatusOK, "Hello world") },
|
||||
)
|
||||
}
|
||||
|
||||
sessionV1 := v1.Group("/session")
|
||||
{
|
||||
sessionV1.POST("/create", func(ctx *gin.Context) { c.Session.Create(ctx) })
|
||||
sessionV1.Use(authn.Authn(cache))
|
||||
sessionV1.POST("/delete", func(ctx *gin.Context) { c.Session.Delete(ctx) })
|
||||
}
|
||||
|
||||
v1.POST("/session/create", func(ctx *gin.Context) { c.Session.Create(ctx) })
|
||||
}
|
||||
|
||||
return engine
|
||||
|
@ -23,10 +23,8 @@
|
||||
package registry
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/adapter/controller"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// registry is an implementation of Registry interface.
|
||||
@ -34,8 +32,7 @@ import (
|
||||
// It might holds other drivers when the projects grows. For example
|
||||
// the object needed to connect to Redis or Kafka.
|
||||
type registry struct {
|
||||
db *sql.DB
|
||||
cache core.Cache
|
||||
db *pgx.Conn
|
||||
}
|
||||
|
||||
// Registry returns a new app controller that will be used by main()/run()
|
||||
@ -46,8 +43,8 @@ type Registry interface {
|
||||
}
|
||||
|
||||
// NewRegistry returns a new Registry's implementation.
|
||||
func NewRegistry(db *sql.DB, cache core.Cache) Registry {
|
||||
return ®istry{db: db, cache: cache}
|
||||
func NewRegistry(db *pgx.Conn) Registry {
|
||||
return ®istry{db: db}
|
||||
}
|
||||
|
||||
// NewAppController creates a new AppController with controller struct for
|
||||
|
@ -31,5 +31,5 @@ import (
|
||||
// NewSessionController returns a session controller's implementation
|
||||
func (r *registry) NewSessionController() controller.Session {
|
||||
u := usecase.NewUserUsecase(repo.NewUserRepository(r.db), repo.NewDBRepository(r.db))
|
||||
return controller.NewSessionController(u, r.cache)
|
||||
return controller.NewSessionController(u)
|
||||
}
|
||||
|
@ -1,34 +0,0 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Cache interface {
|
||||
Get(ctx context.Context, key string) (string, error)
|
||||
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
|
||||
Close() error
|
||||
}
|
@ -20,15 +20,13 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package authn
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/shared"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/token"
|
||||
"github.com/gin-gonic/gin"
|
||||
@ -40,14 +38,8 @@ var ErrTokenInvalid = &errno.Errno{
|
||||
Message: "invalid token",
|
||||
}
|
||||
|
||||
var ErrLoggedOut = &errno.Errno{
|
||||
HTTP: http.StatusUnauthorized,
|
||||
Code: errno.ErrorCode(errno.AuthFailureCode, "LoggedOut"),
|
||||
Message: "logged out, please log in",
|
||||
}
|
||||
|
||||
// Authn authenticates a user's access by validating their token.
|
||||
func Authn(cache core.Cache) gin.HandlerFunc {
|
||||
func Authn() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
tk, err := token.ParseRequest(ctx)
|
||||
if err != nil || tk == nil {
|
||||
@ -56,20 +48,7 @@ func Authn(cache core.Cache) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
key := fmt.Sprintf("jwt:%s", tk.Identity)
|
||||
|
||||
val, err := cache.Get(ctx, key)
|
||||
if err != nil {
|
||||
log.ErrorLog("cache get token", "err", err)
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
if val != "" {
|
||||
// blacklist
|
||||
core.WriteResponse(ctx, ErrLoggedOut, nil)
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
// TODO: check if the key is on logout blacklist.
|
||||
|
||||
ctx.Header(shared.XUserName, tk.Identity)
|
||||
ctx.Next()
|
@ -1,117 +0,0 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package authn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/shared"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/test"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/token"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var loggedOutID string
|
||||
|
||||
type testCache struct{}
|
||||
|
||||
func (tc *testCache) Get(ctx context.Context, key string) (string, error) {
|
||||
loggedOutKey := fmt.Sprintf("jwt:%s", loggedOutID)
|
||||
if key == loggedOutKey {
|
||||
return "found", nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (c *testCache) Set(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
value interface{},
|
||||
expiration time.Duration,
|
||||
) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *testCache) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestAuthn(t *testing.T) {
|
||||
token.Init("secret", 1*time.Second)
|
||||
tk, _ := token.Sign("user")
|
||||
|
||||
tkParsed, _ := token.Parse(tk)
|
||||
loggedOutID = tkParsed.Identity
|
||||
|
||||
cache := &testCache{}
|
||||
|
||||
t.Run("token found in cache", func(t *testing.T) {
|
||||
r := gin.New()
|
||||
r.Use(Authn(cache))
|
||||
|
||||
r.GET("/example", func(c *gin.Context) {
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
res := test.PerformRequest(
|
||||
t,
|
||||
r,
|
||||
"GET",
|
||||
"/example",
|
||||
nil,
|
||||
test.Header{Key: shared.XUserName, Value: "user"},
|
||||
test.Header{Key: "Authorization", Value: fmt.Sprintf("Bearer %s", tk)},
|
||||
)
|
||||
assert.Equal(t, http.StatusUnauthorized, res.Result().StatusCode, res.Body)
|
||||
|
||||
var err errno.Errno
|
||||
json.NewDecoder(res.Result().Body).Decode(&err)
|
||||
assert.Equal(t, "AuthFailure.LoggedOut", err.Code)
|
||||
})
|
||||
|
||||
t.Run("token not found in cache", func(t *testing.T) {
|
||||
newTk, _ := token.Sign("user2")
|
||||
r := gin.New()
|
||||
r.Use(Authn(cache))
|
||||
|
||||
r.GET("/example", func(c *gin.Context) {
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
res := test.PerformRequest(
|
||||
t,
|
||||
r,
|
||||
"GET",
|
||||
"/example",
|
||||
nil,
|
||||
test.Header{Key: shared.XUserName, Value: "user2"},
|
||||
test.Header{Key: "Authorization", Value: fmt.Sprintf("Bearer %s", newTk)},
|
||||
)
|
||||
assert.Equal(t, http.StatusOK, res.Result().StatusCode, res.Body)
|
||||
})
|
||||
}
|
@ -1,25 +1,3 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package shared
|
||||
|
||||
const (
|
||||
|
@ -43,7 +43,6 @@ type Claims struct {
|
||||
}
|
||||
|
||||
type TokenResp struct {
|
||||
Raw string
|
||||
Identity string
|
||||
Expiry time.Time
|
||||
}
|
||||
@ -92,7 +91,6 @@ func Parse(tokenString string) (*TokenResp, error) {
|
||||
|
||||
if claims, ok := token.Claims.(*Claims); ok {
|
||||
return &TokenResp{
|
||||
tokenString,
|
||||
claims.IdentityKey,
|
||||
claims.ExpiresAt.Time,
|
||||
}, nil
|
||||
|
Loading…
x
Reference in New Issue
Block a user