Skip to content

Commit 8f7c1ee

Browse files
committed
feat: shortcut
1 parent f505cc0 commit 8f7c1ee

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

services/auth/shortcut.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright 2023 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package auth
5+
6+
import (
7+
"net/http"
8+
9+
user_model "code.gitea.io/gitea/models/user"
10+
)
11+
12+
// Shortcut is a group of verification methods that is like Group.
13+
// It tries each method in order and returns the first non-nil user,
14+
// but it never returns error even if some method returns error.
15+
// It is useful for some methods that share the same protocol, shortcut can check them first.
16+
// For example, OAuth2 and conan.Auth both read token from "Authorization: Bearer <token>" header,
17+
// If OAuth2 returns error, it is possible that the token is for conan.Auth but it has no chance to check.
18+
// And Shortcut solves this problem by:
19+
//
20+
// NewGroup(
21+
// Shortcut{&OAuth2, &conan.Auth},
22+
// &OAuth2,
23+
// &auth.Basic{},
24+
// &nuget.Auth{},
25+
// &conan.Auth{},
26+
// &chef.Auth{},
27+
// )
28+
//
29+
// Since Shortcut will set "AuthedMethod" in DataStore if any method returns non-nil user,
30+
// so it is unnecessary to implement Named interface for it, the "name" of Shortcut should never be stored as "AuthedMethod".
31+
type Shortcut []Method
32+
33+
func (s Shortcut) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) {
34+
for _, method := range s {
35+
user, err := method.Verify(req, w, store, sess)
36+
if err != nil {
37+
// Don't return error, just try next method
38+
continue
39+
}
40+
41+
if user != nil {
42+
if store.GetData()["AuthedMethod"] == nil {
43+
if named, ok := method.(Named); ok {
44+
store.GetData()["AuthedMethod"] = named.Name()
45+
}
46+
}
47+
return user, nil
48+
}
49+
}
50+
51+
return nil, nil
52+
}

0 commit comments

Comments
 (0)