feat: support basic user system
This commit is contained in:
22
internal/config/config.go
Normal file
22
internal/config/config.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.starryskymeow.cn/B309/datamarket/internal/repository"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
JWTAuth *jwtauth.JWTAuth
|
||||
}
|
||||
|
||||
func New(repo *repository.Queries) (*Config, error) {
|
||||
config := new(Config)
|
||||
cfg, err := repo.GetConfig(context.Background())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.JWTAuth = jwtauth.New(cfg.JwtAlg, []byte(cfg.JwtSignKey), nil)
|
||||
return config, nil
|
||||
}
|
||||
73
internal/handler/auth.go
Normal file
73
internal/handler/auth.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"gitea.starryskymeow.cn/B309/datamarket/internal/service"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
"github.com/go-chi/render"
|
||||
)
|
||||
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
const usernameExpr = `^\S{3,32}$`
|
||||
const passwordExpr = `^\S{8,64}$`
|
||||
|
||||
func (req *LoginRequest) Bind(_ *http.Request) error {
|
||||
// username
|
||||
if ok, _ := regexp.MatchString(usernameExpr, req.Username); !ok {
|
||||
return fmt.Errorf("invalid username, must match %q", usernameExpr)
|
||||
}
|
||||
|
||||
// password
|
||||
if ok, _ := regexp.MatchString(passwordExpr, req.Password); !ok {
|
||||
return fmt.Errorf("invalid password, must match %q", passwordExpr)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoginHandler POST /api/auth/login
|
||||
func LoginHandler(auth service.AuthService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
req := &LoginRequest{}
|
||||
if err := render.Bind(r, req); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
renderServiceError(w, r, err)
|
||||
return
|
||||
}
|
||||
user, err := auth.VerifyUser(r.Context(), service.VerifyUserInput{
|
||||
Username: req.Username,
|
||||
Password: req.Password,
|
||||
})
|
||||
if err != nil {
|
||||
renderServiceError(w, r, err)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "jwt",
|
||||
Value: user.Token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: true,
|
||||
MaxAge: 60 * 60 * 24, // 1d
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
renderSuccess(w, r, http.StatusAccepted, "登录成功", user)
|
||||
}
|
||||
}
|
||||
|
||||
func MeHandler(auth service.AuthService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, claims, err := jwtauth.FromContext(r.Context())
|
||||
if err != nil {
|
||||
renderServiceError(w, r, err)
|
||||
}
|
||||
renderSuccess(w, r, http.StatusOK, "logged in", claims)
|
||||
}
|
||||
}
|
||||
28
internal/repository/config.sql.go
Normal file
28
internal/repository/config.sql.go
Normal file
@@ -0,0 +1,28 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.30.0
|
||||
// source: config.sql
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const getConfig = `-- name: GetConfig :one
|
||||
SELECT id, "Jwt.Alg", "Jwt.SignKey", "Jwt.VerifyKye"
|
||||
FROM config
|
||||
WHERE id = 0
|
||||
`
|
||||
|
||||
func (q *Queries) GetConfig(ctx context.Context) (Config, error) {
|
||||
row := q.db.QueryRow(ctx, getConfig)
|
||||
var i Config
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.JwtAlg,
|
||||
&i.JwtSignKey,
|
||||
&i.JwtVerifyKye,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -97,7 +97,7 @@ INSERT INTO buyer_requests (
|
||||
request_status
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING id, asset_id, task_type, model_type, buyer_budget_min, buyer_budget_max, privacy_requirement, usage_purpose, request_note, request_status, created_at, updated_at
|
||||
RETURNING id, asset_id, task_type, model_type, buyer_budget_min, buyer_budget_max, privacy_requirement, usage_purpose, request_note, request_status, created_at, updated_at, user_id
|
||||
`
|
||||
|
||||
type CreateBuyerRequestParams struct {
|
||||
@@ -138,6 +138,7 @@ func (q *Queries) CreateBuyerRequest(ctx context.Context, arg CreateBuyerRequest
|
||||
&i.RequestStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.UserID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -195,7 +196,33 @@ type CreateDataAssetParams struct {
|
||||
AssetStatus string `json:"asset_status"`
|
||||
}
|
||||
|
||||
func (q *Queries) CreateDataAsset(ctx context.Context, arg CreateDataAssetParams) (DataAsset, error) {
|
||||
type CreateDataAssetRow struct {
|
||||
ID pgtype.UUID `json:"id"`
|
||||
AssetName string `json:"asset_name"`
|
||||
AssetType string `json:"asset_type"`
|
||||
Domain string `json:"domain"`
|
||||
ApplicationScene pgtype.Text `json:"application_scene"`
|
||||
DataDescription string `json:"data_description"`
|
||||
DataScale string `json:"data_scale"`
|
||||
CollectionMethod string `json:"collection_method"`
|
||||
LabelingStatus pgtype.Text `json:"labeling_status"`
|
||||
UpdateFrequency pgtype.Text `json:"update_frequency"`
|
||||
PrivacyLevel string `json:"privacy_level"`
|
||||
PermissionMode string `json:"permission_mode"`
|
||||
SupportsValidation bool `json:"supports_validation"`
|
||||
SellerExpectedPriceMin pgtype.Numeric `json:"seller_expected_price_min"`
|
||||
SellerExpectedPriceMax pgtype.Numeric `json:"seller_expected_price_max"`
|
||||
QualityLevel pgtype.Text `json:"quality_level"`
|
||||
ScarcityLevel pgtype.Text `json:"scarcity_level"`
|
||||
BaseValueScore pgtype.Numeric `json:"base_value_score"`
|
||||
BasePriceMin pgtype.Numeric `json:"base_price_min"`
|
||||
BasePriceMax pgtype.Numeric `json:"base_price_max"`
|
||||
AssetStatus string `json:"asset_status"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (q *Queries) CreateDataAsset(ctx context.Context, arg CreateDataAssetParams) (CreateDataAssetRow, error) {
|
||||
row := q.db.QueryRow(ctx, createDataAsset,
|
||||
arg.AssetName,
|
||||
arg.AssetType,
|
||||
@@ -218,7 +245,7 @@ func (q *Queries) CreateDataAsset(ctx context.Context, arg CreateDataAssetParams
|
||||
arg.BasePriceMax,
|
||||
arg.AssetStatus,
|
||||
)
|
||||
var i DataAsset
|
||||
var i CreateDataAssetRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.AssetName,
|
||||
@@ -262,7 +289,7 @@ INSERT INTO orders (
|
||||
order_status
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
RETURNING id, asset_id, request_id, pricing_id, validation_id, asset_name, current_price, negotiation_min, negotiation_max, validation_used, delivery_mode, order_status, order_created_at, order_updated_at
|
||||
RETURNING id, asset_id, request_id, pricing_id, validation_id, asset_name, current_price, negotiation_min, negotiation_max, validation_used, delivery_mode, order_status, order_created_at, order_updated_at, user_id
|
||||
`
|
||||
|
||||
type CreateOrderParams struct {
|
||||
@@ -309,6 +336,7 @@ func (q *Queries) CreateOrder(ctx context.Context, arg CreateOrderParams) (Order
|
||||
&i.OrderStatus,
|
||||
&i.OrderCreatedAt,
|
||||
&i.OrderUpdatedAt,
|
||||
&i.UserID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -329,7 +357,7 @@ INSERT INTO pricing_results (
|
||||
pricing_status
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
||||
RETURNING id, asset_id, request_id, scenario_value_score, scenario_price_min, scenario_price_max, suggested_price, success_probability, pricing_reason_1, pricing_reason_2, pricing_reason_3, verification_suggestion, pricing_status, created_at, updated_at
|
||||
RETURNING id, asset_id, request_id, scenario_value_score, scenario_price_min, scenario_price_max, suggested_price, success_probability, pricing_reason_1, pricing_reason_2, pricing_reason_3, verification_suggestion, pricing_status, created_at, updated_at, agent_task_match_explanation, agent_risk_advice, agent_budget_advice, agent_next_action
|
||||
`
|
||||
|
||||
type CreatePricingResultParams struct {
|
||||
@@ -379,6 +407,10 @@ func (q *Queries) CreatePricingResult(ctx context.Context, arg CreatePricingResu
|
||||
&i.PricingStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.AgentTaskMatchExplanation,
|
||||
&i.AgentRiskAdvice,
|
||||
&i.AgentBudgetAdvice,
|
||||
&i.AgentNextAction,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -397,7 +429,7 @@ INSERT INTO validations (
|
||||
validation_finished_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING id, asset_id, request_id, validation_type, validation_requested, validation_status, validation_signal, validation_score, risk_warning, continue_recommendation, validation_created_at, validation_finished_at
|
||||
RETURNING id, asset_id, request_id, validation_type, validation_requested, validation_status, validation_signal, validation_score, risk_warning, continue_recommendation, validation_created_at, validation_finished_at, agent_validation_explanation, agent_continue_trade_advice, agent_delivery_advice, agent_risk_notice
|
||||
`
|
||||
|
||||
type CreateValidationParams struct {
|
||||
@@ -440,12 +472,16 @@ func (q *Queries) CreateValidation(ctx context.Context, arg CreateValidationPara
|
||||
&i.ContinueRecommendation,
|
||||
&i.ValidationCreatedAt,
|
||||
&i.ValidationFinishedAt,
|
||||
&i.AgentValidationExplanation,
|
||||
&i.AgentContinueTradeAdvice,
|
||||
&i.AgentDeliveryAdvice,
|
||||
&i.AgentRiskNotice,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getBuyerRequest = `-- name: GetBuyerRequest :one
|
||||
SELECT id, asset_id, task_type, model_type, buyer_budget_min, buyer_budget_max, privacy_requirement, usage_purpose, request_note, request_status, created_at, updated_at
|
||||
SELECT id, asset_id, task_type, model_type, buyer_budget_min, buyer_budget_max, privacy_requirement, usage_purpose, request_note, request_status, created_at, updated_at, user_id
|
||||
FROM buyer_requests
|
||||
WHERE id = $1
|
||||
`
|
||||
@@ -466,12 +502,13 @@ func (q *Queries) GetBuyerRequest(ctx context.Context, id pgtype.UUID) (BuyerReq
|
||||
&i.RequestStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.UserID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getDataAsset = `-- name: GetDataAsset :one
|
||||
SELECT id, asset_name, asset_type, domain, application_scene, data_description, data_scale, collection_method, labeling_status, update_frequency, privacy_level, permission_mode, supports_validation, seller_expected_price_min, seller_expected_price_max, quality_level, scarcity_level, base_value_score, base_price_min, base_price_max, asset_status, created_at, updated_at
|
||||
SELECT id, asset_name, asset_type, domain, application_scene, data_description, data_scale, collection_method, labeling_status, update_frequency, privacy_level, permission_mode, supports_validation, seller_expected_price_min, seller_expected_price_max, quality_level, scarcity_level, base_value_score, base_price_min, base_price_max, asset_status, created_at, updated_at, user_id, agent_asset_summary, agent_recommended_tasks, agent_risk_per_mission_advice, agent_asset_explanation
|
||||
FROM data_assets
|
||||
WHERE id = $1
|
||||
`
|
||||
@@ -503,12 +540,17 @@ func (q *Queries) GetDataAsset(ctx context.Context, id pgtype.UUID) (DataAsset,
|
||||
&i.AssetStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.UserID,
|
||||
&i.AgentAssetSummary,
|
||||
&i.AgentRecommendedTasks,
|
||||
&i.AgentRiskPerMissionAdvice,
|
||||
&i.AgentAssetExplanation,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getOrder = `-- name: GetOrder :one
|
||||
SELECT id, asset_id, request_id, pricing_id, validation_id, asset_name, current_price, negotiation_min, negotiation_max, validation_used, delivery_mode, order_status, order_created_at, order_updated_at
|
||||
SELECT id, asset_id, request_id, pricing_id, validation_id, asset_name, current_price, negotiation_min, negotiation_max, validation_used, delivery_mode, order_status, order_created_at, order_updated_at, user_id
|
||||
FROM orders
|
||||
WHERE id = $1
|
||||
`
|
||||
@@ -531,12 +573,13 @@ func (q *Queries) GetOrder(ctx context.Context, id pgtype.UUID) (Order, error) {
|
||||
&i.OrderStatus,
|
||||
&i.OrderCreatedAt,
|
||||
&i.OrderUpdatedAt,
|
||||
&i.UserID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getPricingResult = `-- name: GetPricingResult :one
|
||||
SELECT id, asset_id, request_id, scenario_value_score, scenario_price_min, scenario_price_max, suggested_price, success_probability, pricing_reason_1, pricing_reason_2, pricing_reason_3, verification_suggestion, pricing_status, created_at, updated_at
|
||||
SELECT id, asset_id, request_id, scenario_value_score, scenario_price_min, scenario_price_max, suggested_price, success_probability, pricing_reason_1, pricing_reason_2, pricing_reason_3, verification_suggestion, pricing_status, created_at, updated_at, agent_task_match_explanation, agent_risk_advice, agent_budget_advice, agent_next_action
|
||||
FROM pricing_results
|
||||
WHERE id = $1
|
||||
`
|
||||
@@ -560,12 +603,16 @@ func (q *Queries) GetPricingResult(ctx context.Context, id pgtype.UUID) (Pricing
|
||||
&i.PricingStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.AgentTaskMatchExplanation,
|
||||
&i.AgentRiskAdvice,
|
||||
&i.AgentBudgetAdvice,
|
||||
&i.AgentNextAction,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getValidation = `-- name: GetValidation :one
|
||||
SELECT id, asset_id, request_id, validation_type, validation_requested, validation_status, validation_signal, validation_score, risk_warning, continue_recommendation, validation_created_at, validation_finished_at
|
||||
SELECT id, asset_id, request_id, validation_type, validation_requested, validation_status, validation_signal, validation_score, risk_warning, continue_recommendation, validation_created_at, validation_finished_at, agent_validation_explanation, agent_continue_trade_advice, agent_delivery_advice, agent_risk_notice
|
||||
FROM validations
|
||||
WHERE id = $1
|
||||
`
|
||||
@@ -586,12 +633,16 @@ func (q *Queries) GetValidation(ctx context.Context, id pgtype.UUID) (Validation
|
||||
&i.ContinueRecommendation,
|
||||
&i.ValidationCreatedAt,
|
||||
&i.ValidationFinishedAt,
|
||||
&i.AgentValidationExplanation,
|
||||
&i.AgentContinueTradeAdvice,
|
||||
&i.AgentDeliveryAdvice,
|
||||
&i.AgentRiskNotice,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listBuyerRequests = `-- name: ListBuyerRequests :many
|
||||
SELECT id, asset_id, task_type, model_type, buyer_budget_min, buyer_budget_max, privacy_requirement, usage_purpose, request_note, request_status, created_at, updated_at
|
||||
SELECT id, asset_id, task_type, model_type, buyer_budget_min, buyer_budget_max, privacy_requirement, usage_purpose, request_note, request_status, created_at, updated_at, user_id
|
||||
FROM buyer_requests
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT $1 OFFSET $2
|
||||
@@ -624,6 +675,7 @@ func (q *Queries) ListBuyerRequests(ctx context.Context, arg ListBuyerRequestsPa
|
||||
&i.RequestStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.UserID,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -636,7 +688,7 @@ func (q *Queries) ListBuyerRequests(ctx context.Context, arg ListBuyerRequestsPa
|
||||
}
|
||||
|
||||
const listDataAssets = `-- name: ListDataAssets :many
|
||||
SELECT id, asset_name, asset_type, domain, application_scene, data_description, data_scale, collection_method, labeling_status, update_frequency, privacy_level, permission_mode, supports_validation, seller_expected_price_min, seller_expected_price_max, quality_level, scarcity_level, base_value_score, base_price_min, base_price_max, asset_status, created_at, updated_at
|
||||
SELECT id, asset_name, asset_type, domain, application_scene, data_description, data_scale, collection_method, labeling_status, update_frequency, privacy_level, permission_mode, supports_validation, seller_expected_price_min, seller_expected_price_max, quality_level, scarcity_level, base_value_score, base_price_min, base_price_max, asset_status, created_at, updated_at, user_id, agent_asset_summary, agent_recommended_tasks, agent_risk_per_mission_advice, agent_asset_explanation
|
||||
FROM data_assets
|
||||
WHERE (
|
||||
NULLIF($3::text, '') IS NULL
|
||||
@@ -714,6 +766,11 @@ func (q *Queries) ListDataAssets(ctx context.Context, arg ListDataAssetsParams)
|
||||
&i.AssetStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.UserID,
|
||||
&i.AgentAssetSummary,
|
||||
&i.AgentRecommendedTasks,
|
||||
&i.AgentRiskPerMissionAdvice,
|
||||
&i.AgentAssetExplanation,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -726,7 +783,7 @@ func (q *Queries) ListDataAssets(ctx context.Context, arg ListDataAssetsParams)
|
||||
}
|
||||
|
||||
const listOrders = `-- name: ListOrders :many
|
||||
SELECT id, asset_id, request_id, pricing_id, validation_id, asset_name, current_price, negotiation_min, negotiation_max, validation_used, delivery_mode, order_status, order_created_at, order_updated_at
|
||||
SELECT id, asset_id, request_id, pricing_id, validation_id, asset_name, current_price, negotiation_min, negotiation_max, validation_used, delivery_mode, order_status, order_created_at, order_updated_at, user_id
|
||||
FROM orders
|
||||
WHERE NULLIF($3::text, '') IS NULL
|
||||
OR order_status = $3::text
|
||||
@@ -764,6 +821,7 @@ func (q *Queries) ListOrders(ctx context.Context, arg ListOrdersParams) ([]Order
|
||||
&i.OrderStatus,
|
||||
&i.OrderCreatedAt,
|
||||
&i.OrderUpdatedAt,
|
||||
&i.UserID,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -776,7 +834,7 @@ func (q *Queries) ListOrders(ctx context.Context, arg ListOrdersParams) ([]Order
|
||||
}
|
||||
|
||||
const listPricingResults = `-- name: ListPricingResults :many
|
||||
SELECT id, asset_id, request_id, scenario_value_score, scenario_price_min, scenario_price_max, suggested_price, success_probability, pricing_reason_1, pricing_reason_2, pricing_reason_3, verification_suggestion, pricing_status, created_at, updated_at
|
||||
SELECT id, asset_id, request_id, scenario_value_score, scenario_price_min, scenario_price_max, suggested_price, success_probability, pricing_reason_1, pricing_reason_2, pricing_reason_3, verification_suggestion, pricing_status, created_at, updated_at, agent_task_match_explanation, agent_risk_advice, agent_budget_advice, agent_next_action
|
||||
FROM pricing_results
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT $1 OFFSET $2
|
||||
@@ -812,6 +870,10 @@ func (q *Queries) ListPricingResults(ctx context.Context, arg ListPricingResults
|
||||
&i.PricingStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.AgentTaskMatchExplanation,
|
||||
&i.AgentRiskAdvice,
|
||||
&i.AgentBudgetAdvice,
|
||||
&i.AgentNextAction,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -824,7 +886,7 @@ func (q *Queries) ListPricingResults(ctx context.Context, arg ListPricingResults
|
||||
}
|
||||
|
||||
const listValidations = `-- name: ListValidations :many
|
||||
SELECT id, asset_id, request_id, validation_type, validation_requested, validation_status, validation_signal, validation_score, risk_warning, continue_recommendation, validation_created_at, validation_finished_at
|
||||
SELECT id, asset_id, request_id, validation_type, validation_requested, validation_status, validation_signal, validation_score, risk_warning, continue_recommendation, validation_created_at, validation_finished_at, agent_validation_explanation, agent_continue_trade_advice, agent_delivery_advice, agent_risk_notice
|
||||
FROM validations
|
||||
ORDER BY validation_created_at DESC, id DESC
|
||||
LIMIT $1 OFFSET $2
|
||||
@@ -857,6 +919,10 @@ func (q *Queries) ListValidations(ctx context.Context, arg ListValidationsParams
|
||||
&i.ContinueRecommendation,
|
||||
&i.ValidationCreatedAt,
|
||||
&i.ValidationFinishedAt,
|
||||
&i.AgentValidationExplanation,
|
||||
&i.AgentContinueTradeAdvice,
|
||||
&i.AgentDeliveryAdvice,
|
||||
&i.AgentRiskNotice,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -873,7 +939,7 @@ UPDATE data_assets
|
||||
SET asset_status = $2,
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, asset_name, asset_type, domain, application_scene, data_description, data_scale, collection_method, labeling_status, update_frequency, privacy_level, permission_mode, supports_validation, seller_expected_price_min, seller_expected_price_max, quality_level, scarcity_level, base_value_score, base_price_min, base_price_max, asset_status, created_at, updated_at
|
||||
RETURNING id, asset_name, asset_type, domain, application_scene, data_description, data_scale, collection_method, labeling_status, update_frequency, privacy_level, permission_mode, supports_validation, seller_expected_price_min, seller_expected_price_max, quality_level, scarcity_level, base_value_score, base_price_min, base_price_max, asset_status, created_at, updated_at, user_id, agent_asset_summary, agent_recommended_tasks, agent_risk_per_mission_advice, agent_asset_explanation
|
||||
`
|
||||
|
||||
type UpdateDataAssetStatusParams struct {
|
||||
@@ -908,6 +974,11 @@ func (q *Queries) UpdateDataAssetStatus(ctx context.Context, arg UpdateDataAsset
|
||||
&i.AssetStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.UserID,
|
||||
&i.AgentAssetSummary,
|
||||
&i.AgentRecommendedTasks,
|
||||
&i.AgentRiskPerMissionAdvice,
|
||||
&i.AgentAssetExplanation,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -917,7 +988,7 @@ UPDATE orders
|
||||
SET order_status = $2,
|
||||
order_updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, asset_id, request_id, pricing_id, validation_id, asset_name, current_price, negotiation_min, negotiation_max, validation_used, delivery_mode, order_status, order_created_at, order_updated_at
|
||||
RETURNING id, asset_id, request_id, pricing_id, validation_id, asset_name, current_price, negotiation_min, negotiation_max, validation_used, delivery_mode, order_status, order_created_at, order_updated_at, user_id
|
||||
`
|
||||
|
||||
type UpdateOrderStatusParams struct {
|
||||
@@ -943,6 +1014,7 @@ func (q *Queries) UpdateOrderStatus(ctx context.Context, arg UpdateOrderStatusPa
|
||||
&i.OrderStatus,
|
||||
&i.OrderCreatedAt,
|
||||
&i.OrderUpdatedAt,
|
||||
&i.UserID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -956,7 +1028,7 @@ SET validation_status = $2,
|
||||
continue_recommendation = $6,
|
||||
validation_finished_at = $7
|
||||
WHERE id = $1
|
||||
RETURNING id, asset_id, request_id, validation_type, validation_requested, validation_status, validation_signal, validation_score, risk_warning, continue_recommendation, validation_created_at, validation_finished_at
|
||||
RETURNING id, asset_id, request_id, validation_type, validation_requested, validation_status, validation_signal, validation_score, risk_warning, continue_recommendation, validation_created_at, validation_finished_at, agent_validation_explanation, agent_continue_trade_advice, agent_delivery_advice, agent_risk_notice
|
||||
`
|
||||
|
||||
type UpdateValidationResultParams struct {
|
||||
@@ -993,6 +1065,10 @@ func (q *Queries) UpdateValidationResult(ctx context.Context, arg UpdateValidati
|
||||
&i.ContinueRecommendation,
|
||||
&i.ValidationCreatedAt,
|
||||
&i.ValidationFinishedAt,
|
||||
&i.AgentValidationExplanation,
|
||||
&i.AgentContinueTradeAdvice,
|
||||
&i.AgentDeliveryAdvice,
|
||||
&i.AgentRiskNotice,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
@@ -21,6 +21,14 @@ type BuyerRequest struct {
|
||||
RequestStatus string `json:"request_status"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
UserID pgtype.UUID `json:"user_id"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
ID int32 `json:"id"`
|
||||
JwtAlg string `json:"Jwt.Alg"`
|
||||
JwtSignKey string `json:"Jwt.SignKey"`
|
||||
JwtVerifyKye pgtype.Text `json:"Jwt.VerifyKye"`
|
||||
}
|
||||
|
||||
type DataAsset struct {
|
||||
@@ -47,6 +55,15 @@ type DataAsset struct {
|
||||
AssetStatus string `json:"asset_status"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
UserID pgtype.UUID `json:"user_id"`
|
||||
// 智能助手对当前资产的简短画像总结
|
||||
AgentAssetSummary pgtype.Text `json:"agent_asset_summary"`
|
||||
// 推荐的适用任务列表
|
||||
AgentRecommendedTasks []byte `json:"agent_recommended_tasks"`
|
||||
// 当前资产更适合的权限与风险建议
|
||||
AgentRiskPerMissionAdvice pgtype.Text `json:"agent_risk_per_mission_advice"`
|
||||
// 为什么该资产当前基础价值较高/中/低
|
||||
AgentAssetExplanation pgtype.Text `json:"agent_asset_explanation"`
|
||||
}
|
||||
|
||||
type Order struct {
|
||||
@@ -64,6 +81,7 @@ type Order struct {
|
||||
OrderStatus string `json:"order_status"`
|
||||
OrderCreatedAt pgtype.Timestamptz `json:"order_created_at"`
|
||||
OrderUpdatedAt pgtype.Timestamptz `json:"order_updated_at"`
|
||||
UserID pgtype.UUID `json:"user_id"`
|
||||
}
|
||||
|
||||
type PricingResult struct {
|
||||
@@ -82,6 +100,25 @@ type PricingResult struct {
|
||||
PricingStatus string `json:"pricing_status"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
// 解释当前数据与任务的匹配关系
|
||||
AgentTaskMatchExplanation pgtype.Text `json:"agent_task_match_explanation"`
|
||||
// 解释当前隐私风险与权限建议
|
||||
AgentRiskAdvice pgtype.Text `json:"agent_risk_advice"`
|
||||
// 根据预算给出的建议
|
||||
AgentBudgetAdvice pgtype.Text `json:"agent_budget_advice"`
|
||||
// 建议接下来做什么
|
||||
AgentNextAction pgtype.Text `json:"agent_next_action"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID pgtype.UUID `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Role string `json:"role"`
|
||||
DisplayName string `json:"display_name"`
|
||||
AccountStatus string `json:"account_status"`
|
||||
LastLoginAt pgtype.Timestamptz `json:"last_login_at"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
}
|
||||
|
||||
type Validation struct {
|
||||
@@ -97,4 +134,12 @@ type Validation struct {
|
||||
ContinueRecommendation pgtype.Text `json:"continue_recommendation"`
|
||||
ValidationCreatedAt pgtype.Timestamptz `json:"validation_created_at"`
|
||||
ValidationFinishedAt pgtype.Timestamptz `json:"validation_finished_at"`
|
||||
// 对当前验证结果的自然语言解释
|
||||
AgentValidationExplanation pgtype.Text `json:"agent_validation_explanation"`
|
||||
// 对是否继续成交的建议
|
||||
AgentContinueTradeAdvice pgtype.Text `json:"agent_continue_trade_advice"`
|
||||
// 对交付方式的建议
|
||||
AgentDeliveryAdvice pgtype.Text `json:"agent_delivery_advice"`
|
||||
// 对后续交易的风险提示
|
||||
AgentRiskNotice pgtype.Text `json:"agent_risk_notice"`
|
||||
}
|
||||
|
||||
32
internal/repository/user.sql.go
Normal file
32
internal/repository/user.sql.go
Normal file
@@ -0,0 +1,32 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.30.0
|
||||
// source: user.sql
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const getUserByUsername = `-- name: GetUserByUsername :one
|
||||
SELECT id, username, password, role, display_name, account_status, last_login_at, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByUsername, username)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.Password,
|
||||
&i.Role,
|
||||
&i.DisplayName,
|
||||
&i.AccountStatus,
|
||||
&i.LastLoginAt,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -4,13 +4,15 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitea.starryskymeow.cn/B309/datamarket/internal/config"
|
||||
"gitea.starryskymeow.cn/B309/datamarket/internal/handler"
|
||||
"gitea.starryskymeow.cn/B309/datamarket/internal/service"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
func New(svc *service.Service) http.Handler {
|
||||
func New(svc *service.Service, config *config.Config) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
r.Use(middleware.RequestID)
|
||||
@@ -49,6 +51,15 @@ func New(svc *service.Service) http.Handler {
|
||||
r.Get("/validations", handler.AdminListValidations(svc))
|
||||
r.Get("/orders", handler.AdminListOrders(svc))
|
||||
})
|
||||
|
||||
r.Route("/auth", func(r chi.Router) {
|
||||
r.Post("/login", handler.LoginHandler(svc))
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Verifier(config.JWTAuth))
|
||||
r.Use(jwtauth.Authenticator(config.JWTAuth))
|
||||
r.Get("/me", handler.MeHandler(svc))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
return r
|
||||
|
||||
44
internal/service/auth.go
Normal file
44
internal/service/auth.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func (s *Service) VerifyUser(ctx context.Context, input VerifyUserInput) (VerifyUserResult, error) {
|
||||
u, err := s.queries.GetUserByUsername(ctx, input.Username)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return VerifyUserResult{}, notFound("user does not exist or password is wrong")
|
||||
}
|
||||
return VerifyUserResult{}, internalError("auth error", nil)
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(input.Password)); err != nil {
|
||||
return VerifyUserResult{}, notFound("user does not exist or password is wrong")
|
||||
}
|
||||
|
||||
// jwt
|
||||
claims := make(map[string]any)
|
||||
claims["userid"] = u.ID.String()
|
||||
claims["username"] = u.Username
|
||||
claims["role"] = u.Role
|
||||
claims["account_status"] = u.AccountStatus
|
||||
jwtauth.SetExpiryIn(claims, 24*time.Hour)
|
||||
jwtauth.SetIssuedNow(claims)
|
||||
|
||||
_, token, _ := s.config.JWTAuth.Encode(claims)
|
||||
|
||||
return VerifyUserResult{
|
||||
Token: token,
|
||||
UserId: u.ID.String(),
|
||||
UserName: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
Role: u.Role,
|
||||
}, nil
|
||||
}
|
||||
13
internal/service/auth_test.go
Normal file
13
internal/service/auth_test.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"log"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestGenerateHashedPassword(t *testing.T) {
|
||||
e, _ := bcrypt.GenerateFromPassword([]byte("1145141919810"), bcrypt.DefaultCost)
|
||||
log.Println(string(e))
|
||||
}
|
||||
1
internal/service/jwt_utils.go
Normal file
1
internal/service/jwt_utils.go
Normal file
@@ -0,0 +1 @@
|
||||
package service
|
||||
@@ -2,13 +2,16 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.starryskymeow.cn/B309/datamarket/internal/config"
|
||||
"gitea.starryskymeow.cn/B309/datamarket/internal/repository"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
@@ -37,12 +40,14 @@ var (
|
||||
|
||||
type Service struct {
|
||||
queries *repository.Queries
|
||||
config *config.Config
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func New(queries *repository.Queries) *Service {
|
||||
func New(queries *repository.Queries, cfg *config.Config) *Service {
|
||||
return &Service{
|
||||
queries: queries,
|
||||
config: cfg,
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
@@ -884,29 +889,33 @@ func timestamptzValue(value time.Time) pgtype.Timestamptz {
|
||||
|
||||
func toAsset(asset repository.DataAsset) Asset {
|
||||
return Asset{
|
||||
ID: asset.ID.String(),
|
||||
AssetName: asset.AssetName,
|
||||
AssetType: asset.AssetType,
|
||||
Domain: asset.Domain,
|
||||
ApplicationScene: toTextPointer(asset.ApplicationScene),
|
||||
DataDescription: asset.DataDescription,
|
||||
DataScale: asset.DataScale,
|
||||
CollectionMethod: asset.CollectionMethod,
|
||||
LabelingStatus: toTextPointer(asset.LabelingStatus),
|
||||
UpdateFrequency: toTextPointer(asset.UpdateFrequency),
|
||||
PrivacyLevel: asset.PrivacyLevel,
|
||||
PermissionMode: asset.PermissionMode,
|
||||
SupportsValidation: asset.SupportsValidation,
|
||||
SellerExpectedPriceMin: toNumericPointer(asset.SellerExpectedPriceMin),
|
||||
SellerExpectedPriceMax: toNumericPointer(asset.SellerExpectedPriceMax),
|
||||
QualityLevel: toTextPointer(asset.QualityLevel),
|
||||
ScarcityLevel: toTextPointer(asset.ScarcityLevel),
|
||||
BaseValueScore: toNumericPointer(asset.BaseValueScore),
|
||||
BasePriceMin: toNumericPointer(asset.BasePriceMin),
|
||||
BasePriceMax: toNumericPointer(asset.BasePriceMax),
|
||||
AssetStatus: asset.AssetStatus,
|
||||
CreatedAt: toTimePointer(asset.CreatedAt),
|
||||
UpdatedAt: toTimePointer(asset.UpdatedAt),
|
||||
ID: asset.ID.String(),
|
||||
AssetName: asset.AssetName,
|
||||
AssetType: asset.AssetType,
|
||||
Domain: asset.Domain,
|
||||
ApplicationScene: toTextPointer(asset.ApplicationScene),
|
||||
DataDescription: asset.DataDescription,
|
||||
DataScale: asset.DataScale,
|
||||
CollectionMethod: asset.CollectionMethod,
|
||||
LabelingStatus: toTextPointer(asset.LabelingStatus),
|
||||
UpdateFrequency: toTextPointer(asset.UpdateFrequency),
|
||||
PrivacyLevel: asset.PrivacyLevel,
|
||||
PermissionMode: asset.PermissionMode,
|
||||
SupportsValidation: asset.SupportsValidation,
|
||||
SellerExpectedPriceMin: toNumericPointer(asset.SellerExpectedPriceMin),
|
||||
SellerExpectedPriceMax: toNumericPointer(asset.SellerExpectedPriceMax),
|
||||
QualityLevel: toTextPointer(asset.QualityLevel),
|
||||
ScarcityLevel: toTextPointer(asset.ScarcityLevel),
|
||||
BaseValueScore: toNumericPointer(asset.BaseValueScore),
|
||||
BasePriceMin: toNumericPointer(asset.BasePriceMin),
|
||||
BasePriceMax: toNumericPointer(asset.BasePriceMax),
|
||||
AssetStatus: asset.AssetStatus,
|
||||
CreatedAt: toTimePointer(asset.CreatedAt),
|
||||
UpdatedAt: toTimePointer(asset.UpdatedAt),
|
||||
AgentAssetSummary: toTextPointer(asset.AgentAssetSummary),
|
||||
AgentRecommendedTasks: toStringArray(asset.AgentRecommendedTasks),
|
||||
AgentRiskPerMissionAdvice: toTextPointer(asset.AgentRiskPerMissionAdvice),
|
||||
AgentAssetExplanation: toTextPointer(asset.AgentAssetExplanation),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -979,6 +988,14 @@ func toTextPointer(value pgtype.Text) *string {
|
||||
return new(value.String)
|
||||
}
|
||||
|
||||
func toStringArray(value []byte) []string {
|
||||
var result []string
|
||||
if err := json.Unmarshal(value, &result); err != nil {
|
||||
slog.Warn(err.Error(), "value", string(value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func toNumericPointer(value pgtype.Numeric) *float64 {
|
||||
if !value.Valid {
|
||||
return nil
|
||||
|
||||
@@ -36,6 +36,14 @@ type Asset struct {
|
||||
AssetStatus string `json:"asset_status"`
|
||||
CreatedAt *time.Time `json:"created_at,omitempty"`
|
||||
UpdatedAt *time.Time `json:"updated_at,omitempty"`
|
||||
// 智能助手对当前资产的简短画像总结
|
||||
AgentAssetSummary *string `json:"agent_asset_summary"`
|
||||
// 推荐的适用任务列表
|
||||
AgentRecommendedTasks []string `json:"agent_recommended_tasks"`
|
||||
// 当前资产更适合的权限与风险建议
|
||||
AgentRiskPerMissionAdvice *string `json:"agent_risk_per_mission_advice"`
|
||||
// 为什么该资产当前基础价值较高/中/低
|
||||
AgentAssetExplanation *string `json:"agent_asset_explanation"`
|
||||
}
|
||||
|
||||
type AssetCreateInput struct {
|
||||
@@ -176,17 +184,20 @@ type AssetService interface {
|
||||
GetAsset(context.Context, string) (Asset, error)
|
||||
ListAssets(context.Context, AssetListInput) (ListResult[Asset], error)
|
||||
UpdateAssetStatus(context.Context, string, StatusUpdate) (AssetStatusResult, error)
|
||||
//DeleteAsset(context.Context, string) (AssetStatusResult, error)
|
||||
}
|
||||
|
||||
type PricingService interface {
|
||||
CreatePricing(context.Context, PricingCreateInput) (Pricing, error)
|
||||
GetPricing(context.Context, string) (Pricing, error)
|
||||
//DeletePricing(context.Context, string) (Pricing, error)
|
||||
}
|
||||
|
||||
type ValidationService interface {
|
||||
CreateValidation(context.Context, ValidationCreateInput) (ValidationCreateResult, error)
|
||||
GetValidation(context.Context, string) (Validation, error)
|
||||
ListValidations(context.Context, ValidationListInput) (ListResult[Validation], error)
|
||||
//DeleteValidation(context.Context, string) (Validation, error)
|
||||
}
|
||||
|
||||
type OrderService interface {
|
||||
@@ -194,4 +205,22 @@ type OrderService interface {
|
||||
GetOrder(context.Context, string) (Order, error)
|
||||
ListOrders(context.Context, OrderListInput) (ListResult[Order], error)
|
||||
UpdateOrderStatus(context.Context, string, StatusUpdate) (OrderCreateResult, error)
|
||||
//DeleteOrder(context.Context, string) (Order, error)
|
||||
}
|
||||
|
||||
type VerifyUserInput struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
type VerifyUserResult struct {
|
||||
Token string `json:"token"`
|
||||
UserId string `json:"user_id"`
|
||||
UserName string `json:"user_name"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
type AuthService interface {
|
||||
VerifyUser(context.Context, VerifyUserInput) (VerifyUserResult, error)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user