I did some updates

This commit is contained in:
Melon 2024-03-04 18:50:13 +00:00
parent 8bbaee1d4a
commit d103f6bcb7
Signed by: melon
GPG Key ID: 6C9D970C50D26A25
15 changed files with 230 additions and 94 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
.idea/
.data/

View File

@ -52,12 +52,16 @@ func main() {
db, err := gomvn.InitDB(filepath.Join(wd, "gomvn.sqlite3.db"))
if err != nil {
log.Fatal("[GoMVN] Error: invalid database: ", err)
return
}
repoBasePath := filepath.Join(wd, "repositories")
err = os.MkdirAll(repoBasePath, os.ModePerm)
if err != nil {
log.Fatal("[GoMVN] Error: failed to create repositories directory: ", err)
}
srv := &http.Server{
Addr: config.Listen,
Handler: routes.Router(db, config.Name, config.Repository),
Handler: routes.Router(db, config.Name, repoBasePath, config.Repository),
ReadTimeout: time.Minute,
ReadHeaderTimeout: time.Minute,
WriteTimeout: time.Minute,

View File

@ -1,28 +1,7 @@
CREATE TABLE artifacts
(
mvn_group TEXT NOT NULL,
artifact TEXT NOT NULL,
version TEXT NOT NULL,
modified TEXT NOT NULL
);
CREATE TABLE paths
(
user_id INTEGER UNIQUE,
path TEXT PRIMARY KEY,
deploy TINYINT,
created_at DATETIME,
updated_at DATETIME,
FOREIGN KEY (user_id) REFERENCES users (id)
);
CREATE TABLE users
(
id INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
admin TINYINT,
token_hash TEXT NOT NULL,
created_at DATETIME,
updated_at DATETIME
admin BOOLEAN NOT NULL,
token_hash TEXT NOT NULL
);

View File

@ -4,30 +4,11 @@
package database
import (
"database/sql"
)
type Artifact struct {
MvnGroup string `json:"mvn_group"`
Artifact string `json:"artifact"`
Version string `json:"version"`
Modified string `json:"modified"`
}
type Path struct {
UserID sql.NullInt64 `json:"user_id"`
Path string `json:"path"`
Deploy sql.NullInt64 `json:"deploy"`
CreatedAt sql.NullTime `json:"created_at"`
UpdatedAt sql.NullTime `json:"updated_at"`
}
import ()
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Admin sql.NullInt64 `json:"admin"`
Admin bool `json:"admin"`
TokenHash string `json:"token_hash"`
CreatedAt sql.NullTime `json:"created_at"`
UpdatedAt sql.NullTime `json:"updated_at"`
}

View File

@ -8,10 +8,27 @@ FROM users
WHERE admin = 1
AND token_hash = ?;
-- name: IsValid :one
SELECT 1
FROM users
WHERE token_hash = ?;
-- name: GetAllUsers :many
SELECT id, name, admin, created_at, updated_at
SELECT id, name
FROM users;
-- name: CreateUser :execlastid
INSERT INTO users (name, admin, token_hash, created_at, updated_at)
VALUES (?, ?, ?, ?, ?);
INSERT INTO users (name, admin, token_hash)
VALUES (?, ?, ?);
-- name: RefreshUserToken :exec
UPDATE users
SET token_hash =?
WHERE id = ?
AND token_hash = ?;
-- name: CheckUserDetails :one
SELECT 1
FROM users
WHERE name = ?
AND token_hash = ?;

View File

@ -0,0 +1,10 @@
package types
import "time"
type Artifact struct {
MvnGroup string `json:"mvn_group"`
Artifact string `json:"artifact"`
Version string `json:"version"`
Modified time.Time `json:"modified"`
}

View File

@ -7,9 +7,27 @@ package database
import (
"context"
"database/sql"
)
const checkUserDetails = `-- name: CheckUserDetails :one
SELECT 1
FROM users
WHERE name = ?
AND token_hash = ?
`
type CheckUserDetailsParams struct {
Name string `json:"name"`
TokenHash string `json:"token_hash"`
}
func (q *Queries) CheckUserDetails(ctx context.Context, arg CheckUserDetailsParams) (int64, error) {
row := q.db.QueryRowContext(ctx, checkUserDetails, arg.Name, arg.TokenHash)
var column_1 int64
err := row.Scan(&column_1)
return column_1, err
}
const countUsers = `-- name: CountUsers :one
SELECT count(*)
FROM users
@ -23,26 +41,18 @@ func (q *Queries) CountUsers(ctx context.Context) (int64, error) {
}
const createUser = `-- name: CreateUser :execlastid
INSERT INTO users (name, admin, token_hash, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
INSERT INTO users (name, admin, token_hash)
VALUES (?, ?, ?)
`
type CreateUserParams struct {
Name string `json:"name"`
Admin sql.NullInt64 `json:"admin"`
Admin bool `json:"admin"`
TokenHash string `json:"token_hash"`
CreatedAt sql.NullTime `json:"created_at"`
UpdatedAt sql.NullTime `json:"updated_at"`
}
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (int64, error) {
result, err := q.db.ExecContext(ctx, createUser,
arg.Name,
arg.Admin,
arg.TokenHash,
arg.CreatedAt,
arg.UpdatedAt,
)
result, err := q.db.ExecContext(ctx, createUser, arg.Name, arg.Admin, arg.TokenHash)
if err != nil {
return 0, err
}
@ -50,16 +60,13 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (int64,
}
const getAllUsers = `-- name: GetAllUsers :many
SELECT id, name, admin, created_at, updated_at
SELECT id, name
FROM users
`
type GetAllUsersRow struct {
ID int64 `json:"id"`
Name string `json:"name"`
Admin sql.NullInt64 `json:"admin"`
CreatedAt sql.NullTime `json:"created_at"`
UpdatedAt sql.NullTime `json:"updated_at"`
}
func (q *Queries) GetAllUsers(ctx context.Context) ([]GetAllUsersRow, error) {
@ -71,13 +78,7 @@ func (q *Queries) GetAllUsers(ctx context.Context) ([]GetAllUsersRow, error) {
var items []GetAllUsersRow
for rows.Next() {
var i GetAllUsersRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Admin,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
if err := rows.Scan(&i.ID, &i.Name); err != nil {
return nil, err
}
items = append(items, i)
@ -104,3 +105,34 @@ func (q *Queries) IsAdmin(ctx context.Context, tokenHash string) (int64, error)
err := row.Scan(&column_1)
return column_1, err
}
const isValid = `-- name: IsValid :one
SELECT 1
FROM users
WHERE token_hash = ?
`
func (q *Queries) IsValid(ctx context.Context, tokenHash string) (int64, error) {
row := q.db.QueryRowContext(ctx, isValid, tokenHash)
var column_1 int64
err := row.Scan(&column_1)
return column_1, err
}
const refreshUserToken = `-- name: RefreshUserToken :exec
UPDATE users
SET token_hash =?
WHERE id = ?
AND token_hash = ?
`
type RefreshUserTokenParams struct {
TokenHash string `json:"token_hash"`
ID int64 `json:"id"`
TokenHash_2 string `json:"token_hash_2"`
}
func (q *Queries) RefreshUserToken(ctx context.Context, arg RefreshUserTokenParams) error {
_, err := q.db.ExecContext(ctx, refreshUserToken, arg.TokenHash, arg.ID, arg.TokenHash_2)
return err
}

1
go.mod
View File

@ -6,6 +6,7 @@ require (
github.com/MrMelon54/exit-reload v0.0.1
github.com/golang-migrate/migrate/v4 v4.17.0
github.com/julienschmidt/httprouter v1.3.0
github.com/thanhpk/randstr v1.0.6
gopkg.in/yaml.v3 v3.0.1
)

2
go.sum
View File

@ -19,6 +19,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/thanhpk/randstr v1.0.6 h1:psAOktJFD4vV9NEVb3qkhRSMvYh4ORRaj1+w/hn4B+o=
github.com/thanhpk/randstr v1.0.6/go.mod h1:M/H2P1eNLZzlDwAzpkkkUvoyNNMbzRGhESZuEQk3r0U=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=

Binary file not shown.

View File

@ -1,21 +1,30 @@
package paths
import (
"github.com/1f349/gomvn/database/types"
"os"
"path/filepath"
"strings"
)
func GetRepositories(basePath string, repository []string) map[string][]*entity.Artifact {
result := map[string][]*database.Artifact{}
func GetRepositories(basePath string, repository []string) map[string][]*types.Artifact {
result := map[string][]*types.Artifact{}
for _, repo := range repository {
result[repo] = []*database.Artifact{}
result[repo] = []*types.Artifact{}
repoPath := filepath.Join(basePath, repo)
_ = filepath.Walk(repoPath, func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".pom") {
path = strings.Replace(path, "\\", "/", -1)
path = strings.Replace(path, repoPath+"/", "", 1)
artifact := entity.NewArtifact(path, info.ModTime())
parts := strings.Split(path, "/")
last := len(parts) - 1
artifact := &types.Artifact{
MvnGroup: strings.Join(parts[0:last-2], "."),
Artifact: parts[last-2],
Version: parts[last-1],
Modified: info.ModTime(),
}
result[repo] = append(result[repo], artifact)
}
return nil

View File

@ -1,4 +1,5 @@
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>GoMVN - {{.Name}}</title>
<style>

47
routes/repoauth.go Normal file
View File

@ -0,0 +1,47 @@
package routes
import (
"context"
"encoding/base64"
"github.com/1f349/gomvn/database"
"github.com/julienschmidt/httprouter"
"net/http"
"strings"
)
func (r *routeCtx) repoAuth(next httprouter.Handle) httprouter.Handle {
return func(rw http.ResponseWriter, req *http.Request, params httprouter.Params) {
un, pw, ok := parseBasicBearer(req)
if !ok {
http.Error(rw, "403 Forbidden", http.StatusForbidden)
return
}
isValid, err := r.db.CheckUserDetails(context.Background(), database.CheckUserDetailsParams{
Name: un,
TokenHash: pw,
})
if err != nil || isValid != 1 {
http.Error(rw, "403 Forbidden", http.StatusForbidden)
return
}
next(rw, req, params)
}
}
func parseBasicBearer(req *http.Request) (string, string, bool) {
auth := req.Header.Get("Authorization")
details, ok := strings.CutPrefix(auth, "Basic ")
if !ok {
return "", "", false
}
decBytes, err := base64.StdEncoding.DecodeString(details)
if err != nil {
return "", "", false
}
decStr := string(decBytes)
n := strings.IndexByte(decStr, ':')
if n == -1 {
return "", "", false
}
return decStr[:n], decStr[n+1:], true
}

View File

@ -2,13 +2,17 @@ package routes
import (
_ "embed"
"encoding/json"
"github.com/1f349/gomvn/database"
"github.com/1f349/gomvn/paths"
"github.com/julienschmidt/httprouter"
"github.com/thanhpk/randstr"
"html/template"
"io"
"net/http"
"os"
"path"
"path/filepath"
)
type routeCtx struct {
@ -23,11 +27,62 @@ func Router(db *database.Queries, name, basePath string, repository []string) ht
pUtils := paths.Paths{Repository: repository}
base := routeCtx{db, pUtils, name, basePath, repository}
r := httprouter.New()
r.PUT("/*", base.handlePut)
r.GET("/", base.handleIndex)
r.GET("/*", base.handleGet)
return r
rApi := httprouter.New()
rApi.GET("/users", func(rw http.ResponseWriter, req *http.Request, params httprouter.Params) {
users, err := db.GetAllUsers(req.Context())
if err != nil {
http.Error(rw, "500 Database Error", http.StatusInternalServerError)
return
}
_ = json.NewEncoder(rw).Encode(users)
})
rApi.POST("/users", func(rw http.ResponseWriter, req *http.Request, params httprouter.Params) {
err := req.ParseForm()
if err != nil {
http.Error(rw, "400 Bad Request", http.StatusBadRequest)
return
}
name := req.PostForm.Get("name")
admin := req.PostForm.Has("admin")
hex := randstr.Hex(32)
_, err = db.CreateUser(req.Context(), database.CreateUserParams{
Name: name,
Admin: admin,
TokenHash: hex,
})
if err != nil {
http.Error(rw, "500 Database Error", http.StatusInternalServerError)
return
}
_ = json.NewEncoder(rw).Encode(map[string]any{
"token": hex,
})
})
rWeb := httprouter.New()
rWeb.PUT("/*filepath", base.repoAuth(base.handlePut))
rWeb.GET("/", base.handleIndex)
for _, repo := range repository {
rWeb.ServeFiles(path.Join("/", repo, "*filepath"), http.FS(os.DirFS(filepath.Join(basePath, repo))))
}
mux := http.NewServeMux()
mux.HandleFunc("/api", func(rw http.ResponseWriter, req *http.Request) {
isAdmin, err := db.IsAdmin(req.Context(), req.Header.Get("Authorization"))
if err != nil {
http.Error(rw, "500 Database Error", http.StatusInternalServerError)
return
}
if isAdmin != 1 {
http.Error(rw, "403 Forbidden", http.StatusForbidden)
return
}
rApi.ServeHTTP(rw, req)
})
mux.Handle("/", rWeb)
return mux
}
//go:embed index.go.html

View File

@ -8,6 +8,3 @@ sql:
package: "database"
out: "database"
emit_json_tags: true
overrides:
- column: "builds.meta"
go_type: "*github.com/mrmelon54/mc-upload-api/database/types.BuildMeta"