Skip to content

Commit

Permalink
refactor: http interceptor.
Browse files Browse the repository at this point in the history
  • Loading branch information
cody committed Dec 5, 2024
1 parent f41c4b3 commit 8ad0129
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
15 changes: 6 additions & 9 deletions core/corehttp/corehttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,20 +54,17 @@ func makeHandler(n *core.IpfsNode, l net.Listener, options ...ServeOption) (http
}

err := interceptorBeforeReq(r, n)
if errors.Is(err, ErrorGatewayCidExits) {

if errors.Is(err, ErrGatewayCidExits) {
http.Error(w, "", http.StatusNotFound)
return
}
if err != nil {
// set allow origin
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-Stream-Output, X-Chunked-Output, X-Content-Length")

if errors.Is(err, ErrNotLogin) || errors.Is(err, ErrInvalidToken) || errors.Is(err, ErrTwoStepCheckErr) {
if r.Method != http.MethodOptions {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}

topMux.ServeHTTP(w, r)
Expand Down
13 changes: 8 additions & 5 deletions core/corehttp/corehttp_interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ const defaultTwoStepDuration = 30 * time.Minute
const firstStepUrl = "dashboard/validate"

var (
ErrorGatewayCidExits = errors.New("cid exits")
ErrNotLogin = errors.New("please login")
ErrInvalidToken = errors.New("invalid token")
ErrTwoStepCheckErr = errors.New("please validate your password first")
ErrGatewayCidExits = errors.New("cid exits")
)

func interceptorBeforeReq(r *http.Request, n *core.IpfsNode) error {
Expand All @@ -45,7 +48,7 @@ func interceptorBeforeReq(r *http.Request, n *core.IpfsNode) error {
}

if exits {
return ErrorGatewayCidExits
return ErrGatewayCidExits
}

return nil
Expand All @@ -59,7 +62,7 @@ func twoStepCheckInterceptor(r *http.Request) error {
return nil
}

return errors.New("please validate your password first")
return ErrTwoStepCheckErr
}

func interceptorAfterResp(r *http.Request, w http.ResponseWriter, n *core.IpfsNode) error {
Expand All @@ -80,7 +83,7 @@ func tokenCheckInterceptor(r *http.Request, n *core.IpfsNode) error {
return nil
}
if !commands.IsLogin {
return fmt.Errorf("please login")
return ErrNotLogin
}
args := r.URL.Query()
token := args.Get("token")
Expand All @@ -93,7 +96,7 @@ func tokenCheckInterceptor(r *http.Request, n *core.IpfsNode) error {
return err
}
if claims.PeerId != n.Identity.String() {
return fmt.Errorf("token is invalid")
return ErrInvalidToken
}

return nil
Expand Down

0 comments on commit 8ad0129

Please sign in to comment.