mirror of
https://github.com/thomiceli/opengist.git
synced 2025-06-23 10:17:58 +02:00
Add passkeys support + MFA (#341)
This commit is contained in:
58
internal/auth/webauthn/user.go
Normal file
58
internal/auth/webauthn/user.go
Normal file
@ -0,0 +1,58 @@
|
||||
package webauthn
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"github.com/go-webauthn/webauthn/protocol"
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
*db.User
|
||||
}
|
||||
|
||||
func (u *user) WebAuthnID() []byte {
|
||||
return uintToBytes(u.ID)
|
||||
}
|
||||
|
||||
func (u *user) WebAuthnName() string {
|
||||
return u.Username
|
||||
}
|
||||
|
||||
func (u *user) WebAuthnDisplayName() string {
|
||||
return u.Username
|
||||
}
|
||||
|
||||
func (u *user) WebAuthnCredentials() []webauthn.Credential {
|
||||
dbCreds, err := db.GetAllWACredentialsForUser(u.ID)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return dbCreds
|
||||
}
|
||||
|
||||
func (u *user) Exclusions() []protocol.CredentialDescriptor {
|
||||
creds := u.WebAuthnCredentials()
|
||||
exclusions := make([]protocol.CredentialDescriptor, len(creds))
|
||||
for i, cred := range creds {
|
||||
exclusions[i] = cred.Descriptor()
|
||||
}
|
||||
|
||||
return exclusions
|
||||
}
|
||||
|
||||
func discoverUser(rawID []byte, _ []byte) (webauthn.User, error) {
|
||||
ogUser, err := db.GetUserByCredentialID(rawID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user{User: ogUser}, nil
|
||||
}
|
||||
|
||||
func uintToBytes(n uint) []byte {
|
||||
b := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(b, uint64(n))
|
||||
return b
|
||||
}
|
138
internal/auth/webauthn/webauthn.go
Normal file
138
internal/auth/webauthn/webauthn.go
Normal file
@ -0,0 +1,138 @@
|
||||
package webauthn
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/go-webauthn/webauthn/protocol"
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/thomiceli/opengist/internal/config"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
var webAuthn *webauthn.WebAuthn
|
||||
|
||||
func Init(urlStr string) error {
|
||||
var rpid, rporigin string
|
||||
var err error
|
||||
|
||||
if urlStr == "" {
|
||||
log.Info().Msg("External URL is not set, passkeys RP ID and Origins will be set to localhost")
|
||||
rpid = "localhost"
|
||||
rporigin = "http://localhost" + ":" + config.C.HttpPort
|
||||
} else {
|
||||
urlStruct, err := url.Parse(urlStr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rpid = urlStruct.Hostname()
|
||||
rporigin, err = protocol.FullyQualifiedOrigin(urlStr)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to get fully qualified origin from external URL")
|
||||
}
|
||||
}
|
||||
|
||||
webAuthn, err = webauthn.New(&webauthn.Config{
|
||||
RPDisplayName: "Opengist",
|
||||
RPID: rpid,
|
||||
RPOrigins: []string{rporigin},
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func BeginBinding(dbUser *db.User) (credCreation *protocol.CredentialCreation, jsonSession []byte, err error) {
|
||||
waUser := &user{User: dbUser}
|
||||
credCreation, session, err := webAuthn.BeginRegistration(waUser, webauthn.WithAuthenticatorSelection(
|
||||
protocol.AuthenticatorSelection{
|
||||
ResidentKey: protocol.ResidentKeyRequirementRequired,
|
||||
UserVerification: protocol.VerificationRequired,
|
||||
},
|
||||
), webauthn.WithAppIdExcludeExtension("Opengist"), webauthn.WithExclusions(waUser.Exclusions()))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
jsonSession, _ = json.Marshal(session)
|
||||
return
|
||||
}
|
||||
|
||||
func FinishBinding(dbUser *db.User, jsonSession []byte, response *http.Request) (*webauthn.Credential, error) {
|
||||
waUser := &user{User: dbUser}
|
||||
|
||||
var session webauthn.SessionData
|
||||
_ = json.Unmarshal(jsonSession, &session)
|
||||
|
||||
return webAuthn.FinishRegistration(waUser, session, response)
|
||||
}
|
||||
|
||||
func BeginDiscoverableLogin() (credCreation *protocol.CredentialAssertion, jsonSession []byte, err error) {
|
||||
credCreation, session, err := webAuthn.BeginDiscoverableLogin(
|
||||
webauthn.WithUserVerification(protocol.VerificationPreferred),
|
||||
)
|
||||
|
||||
jsonSession, _ = json.Marshal(session)
|
||||
return
|
||||
}
|
||||
|
||||
func FinishDiscoverableLogin(jsonSession []byte, response *http.Request) (uint, error) {
|
||||
var session webauthn.SessionData
|
||||
_ = json.Unmarshal(jsonSession, &session)
|
||||
|
||||
parsedResponse, err := protocol.ParseCredentialRequestResponse(response)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
waUser, cred, err := webAuthn.ValidatePasskeyLogin(discoverUser, session, parsedResponse)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
dbCredential, err := db.GetCredentialByID(cred.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err = dbCredential.UpdateSignCount(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err = dbCredential.UpdateLastUsedAt(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return waUser.(*user).User.ID, nil
|
||||
}
|
||||
|
||||
func BeginLogin(dbUser *db.User) (credCreation *protocol.CredentialAssertion, jsonSession []byte, err error) {
|
||||
waUser := &user{User: dbUser}
|
||||
credCreation, session, err := webAuthn.BeginLogin(waUser)
|
||||
|
||||
jsonSession, _ = json.Marshal(session)
|
||||
return
|
||||
}
|
||||
|
||||
func FinishLogin(dbUser *db.User, jsonSession []byte, response *http.Request) error {
|
||||
waUser := &user{User: dbUser}
|
||||
|
||||
var session webauthn.SessionData
|
||||
_ = json.Unmarshal(jsonSession, &session)
|
||||
|
||||
cred, err := webAuthn.FinishLogin(waUser, session, response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dbCredential, err := db.GetCredentialByID(cred.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = dbCredential.UpdateSignCount(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = dbCredential.UpdateLastUsedAt(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
@ -3,6 +3,7 @@ package cli
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/thomiceli/opengist/internal/auth/webauthn"
|
||||
"github.com/thomiceli/opengist/internal/config"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/git"
|
||||
@ -118,6 +119,10 @@ func Initialize(ctx *cli.Context) {
|
||||
log.Fatal().Err(err).Msg("Failed to initialize in memory database")
|
||||
}
|
||||
|
||||
if err := webauthn.Init(config.C.ExternalUrl); err != nil {
|
||||
log.Error().Err(err).Msg("Failed to initialize WebAuthn")
|
||||
}
|
||||
|
||||
if config.C.IndexEnabled {
|
||||
log.Info().Msg("Index directory: " + filepath.Join(homePath, config.C.IndexDirname))
|
||||
index.Init(filepath.Join(homePath, config.C.IndexDirname))
|
||||
|
@ -137,7 +137,7 @@ func Setup(dbUri string, sharedCache bool) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = db.AutoMigrate(&User{}, &Gist{}, &SSHKey{}, &AdminSetting{}, &Invitation{}); err != nil {
|
||||
if err = db.AutoMigrate(&User{}, &Gist{}, &SSHKey{}, &AdminSetting{}, &Invitation{}, &WebAuthnCredential{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@ -241,5 +241,5 @@ func DeprecationDBFilename() {
|
||||
}
|
||||
|
||||
func TruncateDatabase() error {
|
||||
return db.Migrator().DropTable("likes", &User{}, "gists", &SSHKey{}, &AdminSetting{}, &Invitation{})
|
||||
return db.Migrator().DropTable("likes", &User{}, "gists", &SSHKey{}, &AdminSetting{}, &Invitation{}, &WebAuthnCredential{})
|
||||
}
|
||||
|
40
internal/db/types.go
Normal file
40
internal/db/types.go
Normal file
@ -0,0 +1,40 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/schema"
|
||||
)
|
||||
|
||||
type binaryData []byte
|
||||
|
||||
func (b *binaryData) Value() (driver.Value, error) {
|
||||
return []byte(*b), nil
|
||||
}
|
||||
|
||||
func (b *binaryData) Scan(value interface{}) error {
|
||||
valBytes, ok := value.([]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("failed to unmarshal BinaryData: %v", value)
|
||||
}
|
||||
*b = valBytes
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*binaryData) GormDataType() string {
|
||||
return "binary_data"
|
||||
}
|
||||
|
||||
func (*binaryData) GormDBDataType(db *gorm.DB, _ *schema.Field) string {
|
||||
switch db.Dialector.Name() {
|
||||
case "sqlite":
|
||||
return "BLOB"
|
||||
case "mysql":
|
||||
return "VARBINARY(1024)"
|
||||
case "postgres":
|
||||
return "BYTEA"
|
||||
default:
|
||||
return "BLOB"
|
||||
}
|
||||
}
|
@ -18,9 +18,10 @@ type User struct {
|
||||
GiteaID string
|
||||
OIDCID string `gorm:"column:oidc_id"`
|
||||
|
||||
Gists []Gist `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;foreignKey:UserID"`
|
||||
SSHKeys []SSHKey `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;foreignKey:UserID"`
|
||||
Liked []Gist `gorm:"many2many:likes;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
|
||||
Gists []Gist `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;foreignKey:UserID"`
|
||||
SSHKeys []SSHKey `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;foreignKey:UserID"`
|
||||
Liked []Gist `gorm:"many2many:likes;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
|
||||
WebAuthnCredentials []WebAuthnCredential `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;foreignKey:UserID"`
|
||||
}
|
||||
|
||||
func (user *User) BeforeDelete(tx *gorm.DB) error {
|
||||
@ -58,6 +59,11 @@ func (user *User) BeforeDelete(tx *gorm.DB) error {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Where("user_id = ?", user.ID).Delete(&WebAuthnCredential{}).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete all gists created by this user
|
||||
return tx.Where("user_id = ?", user.ID).Delete(&Gist{}).Error
|
||||
}
|
||||
@ -200,6 +206,13 @@ func (user *User) DeleteProviderID(provider string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (user *User) HasMFA() (bool, error) {
|
||||
var exists bool
|
||||
err := db.Model(&WebAuthnCredential{}).Select("count(*) > 0").Where("user_id = ?", user.ID).Find(&exists).Error
|
||||
|
||||
return exists, err
|
||||
}
|
||||
|
||||
// -- DTO -- //
|
||||
|
||||
type UserDTO struct {
|
||||
|
149
internal/db/webauth_credential.go
Normal file
149
internal/db/webauth_credential.go
Normal file
@ -0,0 +1,149 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
"time"
|
||||
)
|
||||
|
||||
type WebAuthnCredential struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
Name string
|
||||
UserID uint
|
||||
User User
|
||||
CredentialID binaryData `gorm:"type:binary_data"`
|
||||
PublicKey binaryData `gorm:"type:binary_data"`
|
||||
AttestationType string
|
||||
AAGUID binaryData `gorm:"type:binary_data"`
|
||||
SignCount uint32
|
||||
CloneWarning bool
|
||||
FlagUserPresent bool
|
||||
FlagUserVerified bool
|
||||
FlagBackupEligible bool
|
||||
FlagBackupState bool
|
||||
CreatedAt int64
|
||||
LastUsedAt int64
|
||||
}
|
||||
|
||||
func (*WebAuthnCredential) TableName() string {
|
||||
return "webauthn"
|
||||
}
|
||||
|
||||
func GetAllWACredentialsForUser(userID uint) ([]webauthn.Credential, error) {
|
||||
var creds []WebAuthnCredential
|
||||
err := db.Where("user_id = ?", userID).Find(&creds).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
webCreds := make([]webauthn.Credential, len(creds))
|
||||
for i, cred := range creds {
|
||||
webCreds[i] = webauthn.Credential{
|
||||
ID: cred.CredentialID,
|
||||
PublicKey: cred.PublicKey,
|
||||
AttestationType: cred.AttestationType,
|
||||
Authenticator: webauthn.Authenticator{
|
||||
AAGUID: cred.AAGUID,
|
||||
SignCount: cred.SignCount,
|
||||
CloneWarning: cred.CloneWarning,
|
||||
},
|
||||
Flags: webauthn.CredentialFlags{
|
||||
UserPresent: cred.FlagUserPresent,
|
||||
UserVerified: cred.FlagUserVerified,
|
||||
BackupEligible: cred.FlagBackupEligible,
|
||||
BackupState: cred.FlagBackupState,
|
||||
},
|
||||
}
|
||||
}
|
||||
return webCreds, nil
|
||||
}
|
||||
|
||||
func GetAllCredentialsForUser(userID uint) ([]WebAuthnCredential, error) {
|
||||
var creds []WebAuthnCredential
|
||||
err := db.Where("user_id = ?", userID).Find(&creds).Error
|
||||
return creds, err
|
||||
}
|
||||
|
||||
func GetUserByCredentialID(credID binaryData) (*User, error) {
|
||||
var credential WebAuthnCredential
|
||||
var err error
|
||||
|
||||
switch db.Dialector.Name() {
|
||||
case "postgres":
|
||||
hexCredID := hex.EncodeToString(credID)
|
||||
if err = db.Preload("User").Where("credential_id = decode(?, 'hex')", hexCredID).First(&credential).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "mysql":
|
||||
case "sqlite":
|
||||
hexCredID := hex.EncodeToString(credID)
|
||||
if err = db.Preload("User").Where("credential_id = unhex(?)", hexCredID).First(&credential).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &credential.User, err
|
||||
}
|
||||
|
||||
func GetCredentialByIDDB(id uint) (*WebAuthnCredential, error) {
|
||||
var cred WebAuthnCredential
|
||||
err := db.Where("id = ?", id).First(&cred).Error
|
||||
return &cred, err
|
||||
}
|
||||
|
||||
func GetCredentialByID(id binaryData) (*WebAuthnCredential, error) {
|
||||
var cred WebAuthnCredential
|
||||
var err error
|
||||
|
||||
switch db.Dialector.Name() {
|
||||
case "postgres":
|
||||
hexCredID := hex.EncodeToString(id)
|
||||
if err = db.Where("credential_id = decode(?, 'hex')", hexCredID).First(&cred).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "mysql":
|
||||
case "sqlite":
|
||||
hexCredID := hex.EncodeToString(id)
|
||||
if err = db.Where("credential_id = unhex(?)", hexCredID).First(&cred).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &cred, err
|
||||
}
|
||||
|
||||
func CreateFromCrendential(userID uint, name string, cred *webauthn.Credential) (*WebAuthnCredential, error) {
|
||||
credDb := &WebAuthnCredential{
|
||||
UserID: userID,
|
||||
Name: name,
|
||||
CredentialID: cred.ID,
|
||||
PublicKey: cred.PublicKey,
|
||||
AttestationType: cred.AttestationType,
|
||||
AAGUID: cred.Authenticator.AAGUID,
|
||||
SignCount: cred.Authenticator.SignCount,
|
||||
CloneWarning: cred.Authenticator.CloneWarning,
|
||||
FlagUserPresent: cred.Flags.UserPresent,
|
||||
FlagUserVerified: cred.Flags.UserVerified,
|
||||
FlagBackupEligible: cred.Flags.BackupEligible,
|
||||
FlagBackupState: cred.Flags.BackupState,
|
||||
}
|
||||
err := db.Create(credDb).Error
|
||||
return credDb, err
|
||||
}
|
||||
|
||||
func (w *WebAuthnCredential) UpdateSignCount() error {
|
||||
return db.Model(w).Update("sign_count", w.SignCount).Error
|
||||
}
|
||||
|
||||
func (w *WebAuthnCredential) UpdateLastUsedAt() error {
|
||||
return db.Model(w).Update("last_used_at", time.Now().Unix()).Error
|
||||
}
|
||||
|
||||
func (w *WebAuthnCredential) Delete() error {
|
||||
return db.Delete(w).Error
|
||||
}
|
||||
|
||||
// -- DTO -- //
|
||||
|
||||
type CrendentialDTO struct {
|
||||
PasskeyName string `json:"passkeyname" validate:"max=50"`
|
||||
}
|
@ -143,6 +143,22 @@ auth.password: Password
|
||||
auth.register-instead: Register instead
|
||||
auth.login-instead: Login instead
|
||||
auth.oauth: Continue with %s account
|
||||
auth.mfa: Multi-factor authentication
|
||||
auth.mfa.passkey: Passkey
|
||||
auth.mfa.passkeys: Passkeys
|
||||
auth.mfa.use-passkey: Use passkey
|
||||
auth.mfa.bind-passkey: Bind passkey
|
||||
auth.mfa.login-with-passkey: Login with passkey
|
||||
auth.mfa.waiting-for-passkey-input: Waiting for input from browser interaction...
|
||||
auth.mfa.use-passkey-to-finish: Use a passkey to finish authentication
|
||||
auth.mfa.passkeys-help: Add a passkey to log to your account and to use as an MFA method.
|
||||
auth.mfa.passkey-name: Name
|
||||
auth.mfa.delete-passkey: Delete
|
||||
auth.mfa.passkey-added-at: Added
|
||||
auth.mfa.passkey-never-used: Never used
|
||||
auth.mfa.passkey-last-used: Last used
|
||||
auth.mfa.delete-passkey-confirm: Confirm deletion of passkey
|
||||
|
||||
|
||||
error: Error
|
||||
error.page-not-found: Page not found
|
||||
@ -155,6 +171,7 @@ error.oauth-unsupported: Unsupported provider
|
||||
error.cannot-bind-data: Cannot bind data
|
||||
error.invalid-number: Invalid number
|
||||
error.invalid-character-unescaped: Invalid character unescaped
|
||||
error.not-in-mfa-session: User is not in a MFA session
|
||||
|
||||
header.menu.all: All
|
||||
header.menu.new: New
|
||||
@ -245,6 +262,8 @@ flash.auth.account-unlinked-oauth: Account unlinked from %s
|
||||
flash.auth.user-sshkeys-not-retrievable: Could not get user keys
|
||||
flash.auth.user-sshkeys-not-created: Could not create ssh key
|
||||
flash.auth.must-be-logged-in: You must be logged in to access gists
|
||||
flash.auth.passkey-registred: Passkey %s registered
|
||||
flash.auth.passkey-deleted: Passkey deleted
|
||||
|
||||
flash.gist.visibility-changed: Gist visibility has been changed
|
||||
flash.gist.deleted: Gist has been deleted
|
||||
|
@ -57,7 +57,7 @@ func validateReservedKeywords(fl validator.FieldLevel) bool {
|
||||
name := fl.Field().String()
|
||||
|
||||
restrictedNames := map[string]struct{}{}
|
||||
for _, restrictedName := range []string{"assets", "register", "login", "logout", "settings", "admin-panel", "all", "search", "init", "healthcheck", "preview", "metrics"} {
|
||||
for _, restrictedName := range []string{"assets", "register", "login", "logout", "settings", "admin-panel", "all", "search", "init", "healthcheck", "preview", "metrics", "mfa", "webauthn"} {
|
||||
restrictedNames[restrictedName] = struct{}{}
|
||||
}
|
||||
|
||||
|
@ -1,9 +1,10 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/json"
|
||||
gojson "encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/labstack/echo/v4"
|
||||
@ -14,6 +15,7 @@ import (
|
||||
"github.com/markbates/goth/providers/gitlab"
|
||||
"github.com/markbates/goth/providers/openidConnect"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/thomiceli/opengist/internal/auth/webauthn"
|
||||
"github.com/thomiceli/opengist/internal/config"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/i18n"
|
||||
@ -166,6 +168,17 @@ func processLogin(ctx echo.Context) error {
|
||||
return redirect(ctx, "/login")
|
||||
}
|
||||
|
||||
// handle MFA
|
||||
var hasMFA bool
|
||||
if hasMFA, err = user.HasMFA(); err != nil {
|
||||
return errorRes(500, "Cannot check for user MFA", err)
|
||||
}
|
||||
if hasMFA {
|
||||
sess.Values["mfaID"] = user.ID
|
||||
saveSession(sess, ctx)
|
||||
return redirect(ctx, "/mfa")
|
||||
}
|
||||
|
||||
sess.Values["user"] = user.ID
|
||||
sess.Options.MaxAge = 60 * 60 * 24 * 365 // 1 year
|
||||
saveSession(sess, ctx)
|
||||
@ -174,6 +187,10 @@ func processLogin(ctx echo.Context) error {
|
||||
return redirect(ctx, "/")
|
||||
}
|
||||
|
||||
func mfa(ctx echo.Context) error {
|
||||
return html(ctx, "mfa.html")
|
||||
}
|
||||
|
||||
func oauthCallback(ctx echo.Context) error {
|
||||
user, err := gothic.CompleteUserAuth(ctx.Response(), ctx.Request())
|
||||
if err != nil {
|
||||
@ -376,6 +393,147 @@ func oauthUnlink(ctx echo.Context) error {
|
||||
return redirect(ctx, "/settings")
|
||||
}
|
||||
|
||||
func beginWebAuthnBinding(ctx echo.Context) error {
|
||||
credsCreation, jsonWaSession, err := webauthn.BeginBinding(getUserLogged(ctx))
|
||||
if err != nil {
|
||||
return errorRes(500, "Cannot begin WebAuthn registration", err)
|
||||
}
|
||||
|
||||
sess := getSession(ctx)
|
||||
sess.Values["webauthn_registration_session"] = jsonWaSession
|
||||
sess.Options.MaxAge = 5 * 60 // 5 minutes
|
||||
saveSession(sess, ctx)
|
||||
|
||||
return ctx.JSON(200, credsCreation)
|
||||
}
|
||||
|
||||
func finishWebAuthnBinding(ctx echo.Context) error {
|
||||
sess := getSession(ctx)
|
||||
jsonWaSession, ok := sess.Values["webauthn_registration_session"].([]byte)
|
||||
if !ok {
|
||||
return jsonErrorRes(401, "Cannot get WebAuthn registration session", nil)
|
||||
}
|
||||
|
||||
user := getUserLogged(ctx)
|
||||
|
||||
// extract passkey name from request
|
||||
body, err := io.ReadAll(ctx.Request().Body)
|
||||
if err != nil {
|
||||
return jsonErrorRes(400, "Failed to read request body", err)
|
||||
}
|
||||
ctx.Request().Body.Close()
|
||||
ctx.Request().Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
|
||||
dto := new(db.CrendentialDTO)
|
||||
_ = gojson.Unmarshal(body, &dto)
|
||||
|
||||
if err = ctx.Validate(dto); err != nil {
|
||||
return jsonErrorRes(400, "Invalid request", err)
|
||||
}
|
||||
passkeyName := dto.PasskeyName
|
||||
if passkeyName == "" {
|
||||
passkeyName = "WebAuthn"
|
||||
}
|
||||
|
||||
waCredential, err := webauthn.FinishBinding(user, jsonWaSession, ctx.Request())
|
||||
if err != nil {
|
||||
return jsonErrorRes(403, "Failed binding attempt for passkey", err)
|
||||
}
|
||||
|
||||
if _, err = db.CreateFromCrendential(user.ID, passkeyName, waCredential); err != nil {
|
||||
return jsonErrorRes(500, "Cannot create WebAuthn credential on database", err)
|
||||
}
|
||||
|
||||
delete(sess.Values, "webauthn_registration_session")
|
||||
saveSession(sess, ctx)
|
||||
|
||||
addFlash(ctx, tr(ctx, "flash.auth.passkey-registred", passkeyName), "success")
|
||||
return json(ctx, 200, []string{"OK"})
|
||||
}
|
||||
|
||||
func beginWebAuthnLogin(ctx echo.Context) error {
|
||||
credsCreation, jsonWaSession, err := webauthn.BeginDiscoverableLogin()
|
||||
if err != nil {
|
||||
return jsonErrorRes(401, "Cannot begin WebAuthn login", err)
|
||||
}
|
||||
|
||||
sess := getSession(ctx)
|
||||
sess.Values["webauthn_login_session"] = jsonWaSession
|
||||
sess.Options.MaxAge = 5 * 60 // 5 minutes
|
||||
saveSession(sess, ctx)
|
||||
|
||||
return json(ctx, 200, credsCreation)
|
||||
}
|
||||
|
||||
func finishWebAuthnLogin(ctx echo.Context) error {
|
||||
sess := getSession(ctx)
|
||||
sessionData, ok := sess.Values["webauthn_login_session"].([]byte)
|
||||
if !ok {
|
||||
return jsonErrorRes(401, "Cannot get WebAuthn login session", nil)
|
||||
}
|
||||
|
||||
userID, err := webauthn.FinishDiscoverableLogin(sessionData, ctx.Request())
|
||||
if err != nil {
|
||||
return jsonErrorRes(403, "Failed authentication attempt for passkey", err)
|
||||
}
|
||||
|
||||
sess.Values["user"] = userID
|
||||
sess.Options.MaxAge = 60 * 60 * 24 * 365 // 1 year
|
||||
|
||||
delete(sess.Values, "webauthn_login_session")
|
||||
saveSession(sess, ctx)
|
||||
|
||||
return json(ctx, 200, []string{"OK"})
|
||||
}
|
||||
|
||||
func beginWebAuthnAssertion(ctx echo.Context) error {
|
||||
sess := getSession(ctx)
|
||||
|
||||
ogUser, err := db.GetUserById(sess.Values["mfaID"].(uint))
|
||||
if err != nil {
|
||||
return jsonErrorRes(500, "Cannot get user", err)
|
||||
}
|
||||
|
||||
credsCreation, jsonWaSession, err := webauthn.BeginLogin(ogUser)
|
||||
if err != nil {
|
||||
return jsonErrorRes(401, "Cannot begin WebAuthn login", err)
|
||||
}
|
||||
|
||||
sess.Values["webauthn_assertion_session"] = jsonWaSession
|
||||
sess.Options.MaxAge = 5 * 60 // 5 minutes
|
||||
saveSession(sess, ctx)
|
||||
|
||||
return json(ctx, 200, credsCreation)
|
||||
}
|
||||
|
||||
func finishWebAuthnAssertion(ctx echo.Context) error {
|
||||
sess := getSession(ctx)
|
||||
sessionData, ok := sess.Values["webauthn_assertion_session"].([]byte)
|
||||
if !ok {
|
||||
return jsonErrorRes(401, "Cannot get WebAuthn assertion session", nil)
|
||||
}
|
||||
|
||||
userId := sess.Values["mfaID"].(uint)
|
||||
|
||||
ogUser, err := db.GetUserById(userId)
|
||||
if err != nil {
|
||||
return jsonErrorRes(500, "Cannot get user", err)
|
||||
}
|
||||
|
||||
if err = webauthn.FinishLogin(ogUser, sessionData, ctx.Request()); err != nil {
|
||||
return jsonErrorRes(403, "Failed authentication attempt for passkey", err)
|
||||
}
|
||||
|
||||
sess.Values["user"] = userId
|
||||
sess.Options.MaxAge = 60 * 60 * 24 * 365 // 1 year
|
||||
|
||||
delete(sess.Values, "webauthn_assertion_session")
|
||||
delete(sess.Values, "mfaID")
|
||||
saveSession(sess, ctx)
|
||||
|
||||
return json(ctx, 200, []string{"OK"})
|
||||
}
|
||||
|
||||
func logout(ctx echo.Context) error {
|
||||
deleteSession(ctx)
|
||||
deleteCsrfCookie(ctx)
|
||||
@ -427,7 +585,7 @@ func getAvatarUrlFromProvider(provider string, identifier string) string {
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
err = json.Unmarshal(body, &result)
|
||||
err = gojson.Unmarshal(body, &result)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Cannot unmarshal Gitea response body")
|
||||
return ""
|
||||
|
@ -2,7 +2,7 @@ package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
gojson "encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
htmlpkg "html"
|
||||
@ -215,10 +215,14 @@ func NewServer(isDev bool, sessionsPath string) *Server {
|
||||
}
|
||||
|
||||
e.HTTPErrorHandler = func(er error, ctx echo.Context) {
|
||||
if err, ok := er.(*echo.HTTPError); ok {
|
||||
setData(ctx, "error", err)
|
||||
if errHtml := htmlWithCode(ctx, err.Code, "error.html"); errHtml != nil {
|
||||
log.Fatal().Err(errHtml).Send()
|
||||
if httpErr, ok := er.(*HTMLError); ok {
|
||||
setData(ctx, "error", er)
|
||||
if fatalErr := htmlWithCode(ctx, httpErr.Code, "error.html"); fatalErr != nil {
|
||||
log.Fatal().Err(fatalErr).Send()
|
||||
}
|
||||
} else if httpErr, ok := er.(*JSONError); ok {
|
||||
if fatalErr := json(ctx, httpErr.Code, httpErr); fatalErr != nil {
|
||||
log.Fatal().Err(fatalErr).Send()
|
||||
}
|
||||
} else {
|
||||
log.Fatal().Err(er).Send()
|
||||
@ -238,14 +242,13 @@ func NewServer(isDev bool, sessionsPath string) *Server {
|
||||
{
|
||||
if !dev {
|
||||
g1.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
|
||||
TokenLookup: "form:_csrf",
|
||||
TokenLookup: "form:_csrf,header:X-CSRF-Token",
|
||||
CookiePath: "/",
|
||||
CookieHTTPOnly: true,
|
||||
CookieSameSite: http.SameSiteStrictMode,
|
||||
}))
|
||||
g1.Use(csrfInit)
|
||||
}
|
||||
|
||||
g1.Use(csrfInit)
|
||||
g1.GET("/", create, logged)
|
||||
g1.POST("/", processCreate, logged)
|
||||
g1.GET("/preview", preview, logged)
|
||||
@ -261,12 +264,20 @@ func NewServer(isDev bool, sessionsPath string) *Server {
|
||||
g1.GET("/oauth/:provider", oauth)
|
||||
g1.GET("/oauth/:provider/callback", oauthCallback)
|
||||
g1.GET("/oauth/:provider/unlink", oauthUnlink, logged)
|
||||
g1.POST("/webauthn/bind", beginWebAuthnBinding, logged)
|
||||
g1.POST("/webauthn/bind/finish", finishWebAuthnBinding, logged)
|
||||
g1.POST("/webauthn/login", beginWebAuthnLogin)
|
||||
g1.POST("/webauthn/login/finish", finishWebAuthnLogin)
|
||||
g1.POST("/webauthn/assertion", beginWebAuthnAssertion, inMFASession)
|
||||
g1.POST("/webauthn/assertion/finish", finishWebAuthnAssertion, inMFASession)
|
||||
g1.GET("/mfa", mfa, inMFASession)
|
||||
|
||||
g1.GET("/settings", userSettings, logged)
|
||||
g1.POST("/settings/email", emailProcess, logged)
|
||||
g1.DELETE("/settings/account", accountDeleteProcess, logged)
|
||||
g1.POST("/settings/ssh-keys", sshKeysProcess, logged)
|
||||
g1.DELETE("/settings/ssh-keys/:id", sshKeysDelete, logged)
|
||||
g1.DELETE("/settings/passkeys/:id", passkeyDelete, logged)
|
||||
g1.PUT("/settings/password", passwordProcess, logged)
|
||||
g1.PUT("/settings/username", usernameProcess, logged)
|
||||
g2 := g1.Group("/admin-panel")
|
||||
@ -518,6 +529,17 @@ func logged(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func inMFASession(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(ctx echo.Context) error {
|
||||
sess := getSession(ctx)
|
||||
_, ok := sess.Values["mfaID"].(uint)
|
||||
if !ok {
|
||||
return errorRes(400, tr(ctx, "error.not-in-mfa-session"), nil)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func makeCheckRequireLogin(isSingleGistAccess bool) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(ctx echo.Context) error {
|
||||
@ -564,7 +586,7 @@ func parseManifestEntries() {
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to read manifest.json")
|
||||
}
|
||||
if err = json.Unmarshal(byteValue, &manifestEntries); err != nil {
|
||||
if err = gojson.Unmarshal(byteValue, &manifestEntries); err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to unmarshal manifest.json")
|
||||
}
|
||||
}
|
||||
|
@ -26,8 +26,14 @@ func userSettings(ctx echo.Context) error {
|
||||
return errorRes(500, "Cannot get SSH keys", err)
|
||||
}
|
||||
|
||||
passkeys, err := db.GetAllCredentialsForUser(user.ID)
|
||||
if err != nil {
|
||||
return errorRes(500, "Cannot get WebAuthn credentials", err)
|
||||
}
|
||||
|
||||
setData(ctx, "email", user.Email)
|
||||
setData(ctx, "sshKeys", keys)
|
||||
setData(ctx, "passkeys", passkeys)
|
||||
setData(ctx, "hasPassword", user.Password != "")
|
||||
setData(ctx, "disableForm", getData(ctx, "DisableLoginForm"))
|
||||
setData(ctx, "htmlTitle", trH(ctx, "settings"))
|
||||
@ -127,6 +133,26 @@ func sshKeysDelete(ctx echo.Context) error {
|
||||
return redirect(ctx, "/settings")
|
||||
}
|
||||
|
||||
func passkeyDelete(ctx echo.Context) error {
|
||||
user := getUserLogged(ctx)
|
||||
keyId, err := strconv.Atoi(ctx.Param("id"))
|
||||
if err != nil {
|
||||
return redirect(ctx, "/settings")
|
||||
}
|
||||
|
||||
passkey, err := db.GetCredentialByIDDB(uint(keyId))
|
||||
if err != nil || passkey.UserID != user.ID {
|
||||
return redirect(ctx, "/settings")
|
||||
}
|
||||
|
||||
if err := passkey.Delete(); err != nil {
|
||||
return errorRes(500, "Cannot delete passkey", err)
|
||||
}
|
||||
|
||||
addFlash(ctx, tr(ctx, "flash.auth.passkey-deleted"), "success")
|
||||
return redirect(ctx, "/settings")
|
||||
}
|
||||
|
||||
func passwordProcess(ctx echo.Context) error {
|
||||
user := getUserLogged(ctx)
|
||||
|
||||
|
@ -19,6 +19,14 @@ import (
|
||||
|
||||
type dataTypeKey string
|
||||
|
||||
type HTMLError struct {
|
||||
*echo.HTTPError
|
||||
}
|
||||
|
||||
type JSONError struct {
|
||||
*echo.HTTPError
|
||||
}
|
||||
|
||||
const dataKey dataTypeKey = "data"
|
||||
|
||||
func setData(ctx echo.Context, key string, value any) {
|
||||
@ -46,6 +54,10 @@ func htmlWithCode(ctx echo.Context, code int, template string) error {
|
||||
return ctx.Render(code, template, ctx.Request().Context().Value(dataKey))
|
||||
}
|
||||
|
||||
func json(ctx echo.Context, code int, data any) error {
|
||||
return ctx.JSON(code, data)
|
||||
}
|
||||
|
||||
func redirect(ctx echo.Context, location string) error {
|
||||
return ctx.Redirect(302, config.C.ExternalUrl+location)
|
||||
}
|
||||
@ -64,7 +76,16 @@ func errorRes(code int, message string, err error) error {
|
||||
skipLogger.Error().Err(err).Msg(message)
|
||||
}
|
||||
|
||||
return &echo.HTTPError{Code: code, Message: message, Internal: err}
|
||||
return &HTMLError{&echo.HTTPError{Code: code, Message: message, Internal: err}}
|
||||
}
|
||||
|
||||
func jsonErrorRes(code int, message string, err error) error {
|
||||
if code >= 500 {
|
||||
var skipLogger = log.With().CallerWithSkipFrameCount(3).Logger()
|
||||
skipLogger.Error().Err(err).Msg(message)
|
||||
}
|
||||
|
||||
return &JSONError{&echo.HTTPError{Code: code, Message: message, Internal: err}}
|
||||
}
|
||||
|
||||
func getUserLogged(ctx echo.Context) *db.User {
|
||||
@ -102,14 +123,15 @@ func saveSession(sess *sessions.Session, ctx echo.Context) {
|
||||
func deleteSession(ctx echo.Context) {
|
||||
sess := getSession(ctx)
|
||||
sess.Options.MaxAge = -1
|
||||
sess.Values["user"] = nil
|
||||
saveSession(sess, ctx)
|
||||
}
|
||||
|
||||
func setCsrfHtmlForm(ctx echo.Context) {
|
||||
var csrf string
|
||||
if csrfToken, ok := ctx.Get("csrf").(string); ok {
|
||||
setData(ctx, "csrfHtml", template.HTML(`<input type="hidden" name="_csrf" value="`+csrfToken+`">`))
|
||||
csrf = csrfToken
|
||||
}
|
||||
setData(ctx, "csrfHtml", template.HTML(`<input type="hidden" name="_csrf" value="`+csrf+`">`))
|
||||
}
|
||||
|
||||
func deleteCsrfCookie(ctx echo.Context) {
|
||||
|
Reference in New Issue
Block a user