aboutsummaryrefslogtreecommitdiff
path: root/internal/context
diff options
context:
space:
mode:
authorYang Liu <50459973+ly4096x@users.noreply.github.com>2022-10-22 09:25:36 -0400
committerGitHub <noreply@github.com>2022-10-22 21:25:36 +0800
commitb9f5cfddc18c55eee62e1fb64a254fee9782c46c (patch)
tree01aca35598976c86a63243135ada1abc48275196 /internal/context
parentfd5874b07b73687f90e8cb7b171b67457364ebe9 (diff)
auth: enable authentication by token from password (#7198)
Co-authored-by: Joe Chen <jc@unknwon.io>
Diffstat (limited to 'internal/context')
-rw-r--r--internal/context/auth.go22
1 files changed, 22 insertions, 0 deletions
diff --git a/internal/context/auth.go b/internal/context/auth.go
index 9cb37863..775a3dd8 100644
--- a/internal/context/auth.go
+++ b/internal/context/auth.go
@@ -5,12 +5,14 @@
package context
import (
+ "context"
"net/http"
"net/url"
"strings"
"github.com/go-macaron/csrf"
"github.com/go-macaron/session"
+ "github.com/pkg/errors"
gouuid "github.com/satori/go.uuid"
"gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2"
@@ -229,3 +231,23 @@ func authenticatedUser(ctx *macaron.Context, sess session.Store) (_ *db.User, is
}
return u, false, isTokenAuth
}
+
+// AuthenticateByToken attempts to authenticate a user by the given access
+// token. It returns db.ErrAccessTokenNotExist when the access token does not
+// exist.
+func AuthenticateByToken(ctx context.Context, token string) (*db.User, error) {
+ t, err := db.AccessTokens.GetBySHA1(ctx, token)
+ if err != nil {
+ return nil, errors.Wrap(err, "get access token by SHA1")
+ }
+ if err = db.AccessTokens.Touch(ctx, t.ID); err != nil {
+ // NOTE: There is no need to fail the auth flow if we can't touch the token.
+ log.Error("Failed to touch access token [id: %d]: %v", t.ID, err)
+ }
+
+ user, err := db.Users.GetByID(ctx, t.UserID)
+ if err != nil {
+ return nil, errors.Wrapf(err, "get user by ID [user_id: %d]", t.UserID)
+ }
+ return user, nil
+}