mirror of
https://github.com/thomiceli/opengist.git
synced 2025-07-11 18:31:51 +02:00
Refactor server code (#407)
This commit is contained in:
22
internal/web/handlers/auth/mfa.go
Normal file
22
internal/web/handlers/auth/mfa.go
Normal file
@ -0,0 +1,22 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
)
|
||||
|
||||
func Mfa(ctx *context.Context) error {
|
||||
var err error
|
||||
|
||||
user := db.User{ID: ctx.GetSession().Values["mfaID"].(uint)}
|
||||
|
||||
var hasWebauthn, hasTotp bool
|
||||
if hasWebauthn, hasTotp, err = user.HasMFA(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot check for user MFA", err)
|
||||
}
|
||||
|
||||
ctx.SetData("hasWebauthn", hasWebauthn)
|
||||
ctx.SetData("hasTotp", hasTotp)
|
||||
|
||||
return ctx.Html("mfa.html")
|
||||
}
|
166
internal/web/handlers/auth/oauth.go
Normal file
166
internal/web/handlers/auth/oauth.go
Normal file
@ -0,0 +1,166 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/thomiceli/opengist/internal/auth/oauth"
|
||||
"github.com/thomiceli/opengist/internal/config"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
"golang.org/x/text/cases"
|
||||
"golang.org/x/text/language"
|
||||
"gorm.io/gorm"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func Oauth(ctx *context.Context) error {
|
||||
providerStr := ctx.Param("provider")
|
||||
|
||||
httpProtocol := "http"
|
||||
if ctx.Request().TLS != nil || ctx.Request().Header.Get("X-Forwarded-Proto") == "https" {
|
||||
httpProtocol = "https"
|
||||
}
|
||||
|
||||
forwarded_hdr := ctx.Request().Header.Get("Forwarded")
|
||||
if forwarded_hdr != "" {
|
||||
fields := strings.Split(forwarded_hdr, ";")
|
||||
fwd := make(map[string]string)
|
||||
for _, v := range fields {
|
||||
p := strings.Split(v, "=")
|
||||
fwd[p[0]] = p[1]
|
||||
}
|
||||
val, ok := fwd["proto"]
|
||||
if ok && val == "https" {
|
||||
httpProtocol = "https"
|
||||
}
|
||||
}
|
||||
|
||||
var opengistUrl string
|
||||
if config.C.ExternalUrl != "" {
|
||||
opengistUrl = config.C.ExternalUrl
|
||||
} else {
|
||||
opengistUrl = httpProtocol + "://" + ctx.Request().Host
|
||||
}
|
||||
|
||||
provider, err := oauth.DefineProvider(providerStr, opengistUrl)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(400, ctx.Tr("error.oauth-unsupported"), nil)
|
||||
}
|
||||
|
||||
if err = provider.RegisterProvider(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot create provider", err)
|
||||
}
|
||||
|
||||
provider.BeginAuthHandler(ctx)
|
||||
return nil
|
||||
}
|
||||
|
||||
func OauthCallback(ctx *context.Context) error {
|
||||
provider, err := oauth.CompleteUserAuth(ctx)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(400, ctx.Tr("error.complete-oauth-login", err.Error()), err)
|
||||
}
|
||||
|
||||
currUser := ctx.User
|
||||
// if user is logged in, link account to user and update its avatar URL
|
||||
if currUser != nil {
|
||||
provider.UpdateUserDB(currUser)
|
||||
|
||||
if err = currUser.Update(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot update user "+cases.Title(language.English).String(provider.GetProvider())+" id", err)
|
||||
}
|
||||
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.account-linked-oauth", cases.Title(language.English).String(provider.GetProvider())), "success")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
|
||||
user := provider.GetProviderUser()
|
||||
userDB, err := db.GetUserByProvider(user.UserID, provider.GetProvider())
|
||||
// if user is not in database, create it
|
||||
if err != nil {
|
||||
if ctx.GetData("DisableSignup") == true {
|
||||
return ctx.ErrorRes(403, ctx.Tr("error.signup-disabled"), nil)
|
||||
}
|
||||
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ctx.ErrorRes(500, "Cannot get user", err)
|
||||
}
|
||||
|
||||
if user.NickName == "" {
|
||||
user.NickName = strings.Split(user.Email, "@")[0]
|
||||
}
|
||||
|
||||
userDB = &db.User{
|
||||
Username: user.NickName,
|
||||
Email: user.Email,
|
||||
MD5Hash: fmt.Sprintf("%x", md5.Sum([]byte(strings.ToLower(strings.TrimSpace(user.Email))))),
|
||||
}
|
||||
|
||||
// set provider id and avatar URL
|
||||
provider.UpdateUserDB(userDB)
|
||||
|
||||
if err = userDB.Create(); err != nil {
|
||||
if db.IsUniqueConstraintViolation(err) {
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.username-exists"), "error")
|
||||
return ctx.RedirectTo("/login")
|
||||
}
|
||||
|
||||
return ctx.ErrorRes(500, "Cannot create user", err)
|
||||
}
|
||||
|
||||
if userDB.ID == 1 {
|
||||
if err = userDB.SetAdmin(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot set user admin", err)
|
||||
}
|
||||
}
|
||||
|
||||
keys, err := provider.GetProviderUserSSHKeys()
|
||||
if err != nil {
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.user-sshkeys-not-retrievable"), "error")
|
||||
log.Error().Err(err).Msg("Could not get user keys")
|
||||
} else {
|
||||
for _, key := range keys {
|
||||
sshKey := db.SSHKey{
|
||||
Title: "Added from " + user.Provider,
|
||||
Content: key,
|
||||
User: *userDB,
|
||||
}
|
||||
|
||||
if err = sshKey.Create(); err != nil {
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.user-sshkeys-not-created"), "error")
|
||||
log.Error().Err(err).Msg("Could not create ssh key")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sess := ctx.GetSession()
|
||||
sess.Values["user"] = userDB.ID
|
||||
ctx.SaveSession(sess)
|
||||
ctx.DeleteCsrfCookie()
|
||||
|
||||
return ctx.RedirectTo("/")
|
||||
}
|
||||
|
||||
func OauthUnlink(ctx *context.Context) error {
|
||||
providerStr := ctx.Param("provider")
|
||||
provider, err := oauth.DefineProvider(ctx.Param("provider"), "")
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(400, ctx.Tr("error.oauth-unsupported"), nil)
|
||||
}
|
||||
|
||||
currUser := ctx.User
|
||||
|
||||
if provider.UserHasProvider(currUser) {
|
||||
if err := currUser.DeleteProviderID(providerStr); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot unlink account from "+cases.Title(language.English).String(providerStr), err)
|
||||
}
|
||||
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.account-unlinked-oauth", cases.Title(language.English).String(providerStr)), "success")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
170
internal/web/handlers/auth/password.go
Normal file
170
internal/web/handlers/auth/password.go
Normal file
@ -0,0 +1,170 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
passwordpkg "github.com/thomiceli/opengist/internal/auth/password"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/i18n"
|
||||
"github.com/thomiceli/opengist/internal/validator"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func Register(ctx *context.Context) error {
|
||||
disableSignup := ctx.GetData("DisableSignup")
|
||||
disableForm := ctx.GetData("DisableLoginForm")
|
||||
|
||||
code := ctx.QueryParam("code")
|
||||
if code != "" {
|
||||
if invitation, err := db.GetInvitationByCode(code); err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ctx.ErrorRes(500, "Cannot check for invitation code", err)
|
||||
} else if invitation != nil && invitation.IsUsable() {
|
||||
disableSignup = false
|
||||
}
|
||||
}
|
||||
|
||||
ctx.SetData("title", ctx.TrH("auth.new-account"))
|
||||
ctx.SetData("htmlTitle", ctx.TrH("auth.new-account"))
|
||||
ctx.SetData("disableForm", disableForm)
|
||||
ctx.SetData("disableSignup", disableSignup)
|
||||
ctx.SetData("isLoginPage", false)
|
||||
return ctx.Html("auth_form.html")
|
||||
}
|
||||
|
||||
func ProcessRegister(ctx *context.Context) error {
|
||||
disableSignup := ctx.GetData("DisableSignup")
|
||||
|
||||
code := ctx.QueryParam("code")
|
||||
invitation, err := db.GetInvitationByCode(code)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ctx.ErrorRes(500, "Cannot check for invitation code", err)
|
||||
} else if invitation.ID != 0 && invitation.IsUsable() {
|
||||
disableSignup = false
|
||||
}
|
||||
|
||||
if disableSignup == true {
|
||||
return ctx.ErrorRes(403, ctx.Tr("error.signup-disabled"), nil)
|
||||
}
|
||||
|
||||
if ctx.GetData("DisableLoginForm") == true {
|
||||
return ctx.ErrorRes(403, ctx.Tr("error.signup-disabled-form"), nil)
|
||||
}
|
||||
|
||||
ctx.SetData("title", ctx.TrH("auth.new-account"))
|
||||
ctx.SetData("htmlTitle", ctx.TrH("auth.new-account"))
|
||||
|
||||
sess := ctx.GetSession()
|
||||
|
||||
dto := new(db.UserDTO)
|
||||
if err := ctx.Bind(dto); err != nil {
|
||||
return ctx.ErrorRes(400, ctx.Tr("error.cannot-bind-data"), err)
|
||||
}
|
||||
|
||||
if err := ctx.Validate(dto); err != nil {
|
||||
ctx.AddFlash(validator.ValidationMessages(&err, ctx.GetData("locale").(*i18n.Locale)), "error")
|
||||
return ctx.Html("auth_form.html")
|
||||
}
|
||||
|
||||
if exists, err := db.UserExists(dto.Username); err != nil || exists {
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.username-exists"), "error")
|
||||
return ctx.Html("auth_form.html")
|
||||
}
|
||||
|
||||
user := dto.ToUser()
|
||||
|
||||
password, err := passwordpkg.HashPassword(user.Password)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot hash password", err)
|
||||
}
|
||||
user.Password = password
|
||||
|
||||
if err = user.Create(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot create user", err)
|
||||
}
|
||||
|
||||
if user.ID == 1 {
|
||||
if err = user.SetAdmin(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot set user admin", err)
|
||||
}
|
||||
}
|
||||
|
||||
if invitation.ID != 0 {
|
||||
if err := invitation.Use(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot use invitation", err)
|
||||
}
|
||||
}
|
||||
|
||||
sess.Values["user"] = user.ID
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
return ctx.RedirectTo("/")
|
||||
}
|
||||
|
||||
func Login(ctx *context.Context) error {
|
||||
ctx.SetData("title", ctx.TrH("auth.login"))
|
||||
ctx.SetData("htmlTitle", ctx.TrH("auth.login"))
|
||||
ctx.SetData("disableForm", ctx.GetData("DisableLoginForm"))
|
||||
ctx.SetData("isLoginPage", true)
|
||||
return ctx.Html("auth_form.html")
|
||||
}
|
||||
|
||||
func ProcessLogin(ctx *context.Context) error {
|
||||
if ctx.GetData("DisableLoginForm") == true {
|
||||
return ctx.ErrorRes(403, ctx.Tr("error.login-disabled-form"), nil)
|
||||
}
|
||||
|
||||
var err error
|
||||
sess := ctx.GetSession()
|
||||
|
||||
dto := &db.UserDTO{}
|
||||
if err = ctx.Bind(dto); err != nil {
|
||||
return ctx.ErrorRes(400, ctx.Tr("error.cannot-bind-data"), err)
|
||||
}
|
||||
password := dto.Password
|
||||
|
||||
var user *db.User
|
||||
|
||||
if user, err = db.GetUserByUsername(dto.Username); err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ctx.ErrorRes(500, "Cannot get user", err)
|
||||
}
|
||||
log.Warn().Msg("Invalid HTTP authentication attempt from " + ctx.RealIP())
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.invalid-credentials"), "error")
|
||||
return ctx.RedirectTo("/login")
|
||||
}
|
||||
|
||||
if ok, err := passwordpkg.VerifyPassword(password, user.Password); !ok {
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot check for password", err)
|
||||
}
|
||||
log.Warn().Msg("Invalid HTTP authentication attempt from " + ctx.RealIP())
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.invalid-credentials"), "error")
|
||||
return ctx.RedirectTo("/login")
|
||||
}
|
||||
|
||||
// handle MFA
|
||||
var hasWebauthn, hasTotp bool
|
||||
if hasWebauthn, hasTotp, err = user.HasMFA(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot check for user MFA", err)
|
||||
}
|
||||
if hasWebauthn || hasTotp {
|
||||
sess.Values["mfaID"] = user.ID
|
||||
sess.Options.MaxAge = 5 * 60 // 5 minutes
|
||||
ctx.SaveSession(sess)
|
||||
return ctx.RedirectTo("/mfa")
|
||||
}
|
||||
|
||||
sess.Values["user"] = user.ID
|
||||
sess.Options.MaxAge = 60 * 60 * 24 * 365 // 1 year
|
||||
ctx.SaveSession(sess)
|
||||
ctx.DeleteCsrfCookie()
|
||||
|
||||
return ctx.RedirectTo("/")
|
||||
}
|
||||
|
||||
func Logout(ctx *context.Context) error {
|
||||
ctx.DeleteSession()
|
||||
ctx.DeleteCsrfCookie()
|
||||
return ctx.RedirectTo("/all")
|
||||
}
|
177
internal/web/handlers/auth/totp.go
Normal file
177
internal/web/handlers/auth/totp.go
Normal file
@ -0,0 +1,177 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/thomiceli/opengist/internal/auth/totp"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
func BeginTotp(ctx *context.Context) error {
|
||||
user := ctx.User
|
||||
|
||||
if _, hasTotp, err := user.HasMFA(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot check for user MFA", err)
|
||||
} else if hasTotp {
|
||||
ctx.AddFlash(ctx.Tr("auth.totp.already-enabled"), "error")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
|
||||
ogUrl, err := url.Parse(ctx.GetData("baseHttpUrl").(string))
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot parse base URL", err)
|
||||
}
|
||||
|
||||
sess := ctx.GetSession()
|
||||
generatedSecret, _ := sess.Values["generatedSecret"].([]byte)
|
||||
|
||||
totpSecret, qrcode, err, generatedSecret := totp.GenerateQRCode(ctx.User.Username, ogUrl.Hostname(), generatedSecret)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot generate TOTP QR code", err)
|
||||
}
|
||||
sess.Values["totpSecret"] = totpSecret
|
||||
sess.Values["generatedSecret"] = generatedSecret
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
ctx.SetData("totpSecret", totpSecret)
|
||||
ctx.SetData("totpQrcode", qrcode)
|
||||
|
||||
return ctx.Html("totp.html")
|
||||
|
||||
}
|
||||
|
||||
func FinishTotp(ctx *context.Context) error {
|
||||
user := ctx.User
|
||||
|
||||
if _, hasTotp, err := user.HasMFA(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot check for user MFA", err)
|
||||
} else if hasTotp {
|
||||
ctx.AddFlash(ctx.Tr("auth.totp.already-enabled"), "error")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
|
||||
dto := &db.TOTPDTO{}
|
||||
if err := ctx.Bind(dto); err != nil {
|
||||
return ctx.ErrorRes(400, ctx.Tr("error.cannot-bind-data"), err)
|
||||
}
|
||||
|
||||
if err := ctx.Validate(dto); err != nil {
|
||||
ctx.AddFlash("Invalid secret", "error")
|
||||
return ctx.RedirectTo("/settings/totp/generate")
|
||||
}
|
||||
|
||||
sess := ctx.GetSession()
|
||||
secret, ok := sess.Values["totpSecret"].(string)
|
||||
if !ok {
|
||||
return ctx.ErrorRes(500, "Cannot get TOTP secret from session", nil)
|
||||
}
|
||||
|
||||
if !totp.Validate(dto.Code, secret) {
|
||||
ctx.AddFlash(ctx.Tr("auth.totp.invalid-code"), "error")
|
||||
|
||||
return ctx.RedirectTo("/settings/totp/generate")
|
||||
}
|
||||
|
||||
userTotp := &db.TOTP{
|
||||
UserID: ctx.User.ID,
|
||||
}
|
||||
if err := userTotp.StoreSecret(secret); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot store TOTP secret", err)
|
||||
}
|
||||
|
||||
if err := userTotp.Create(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot create TOTP", err)
|
||||
}
|
||||
|
||||
ctx.AddFlash("TOTP successfully enabled", "success")
|
||||
codes, err := userTotp.GenerateRecoveryCodes()
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot generate recovery codes", err)
|
||||
}
|
||||
|
||||
delete(sess.Values, "totpSecret")
|
||||
delete(sess.Values, "generatedSecret")
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
ctx.SetData("recoveryCodes", codes)
|
||||
return ctx.Html("totp.html")
|
||||
}
|
||||
|
||||
func AssertTotp(ctx *context.Context) error {
|
||||
var err error
|
||||
dto := &db.TOTPDTO{}
|
||||
if err := ctx.Bind(dto); err != nil {
|
||||
return ctx.ErrorRes(400, ctx.Tr("error.cannot-bind-data"), err)
|
||||
}
|
||||
|
||||
if err := ctx.Validate(dto); err != nil {
|
||||
ctx.AddFlash(ctx.Tr("auth.totp.invalid-code"), "error")
|
||||
return ctx.RedirectTo("/mfa")
|
||||
}
|
||||
|
||||
sess := ctx.GetSession()
|
||||
userId := sess.Values["mfaID"].(uint)
|
||||
var userTotp *db.TOTP
|
||||
if userTotp, err = db.GetTOTPByUserID(userId); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot get TOTP by UID", err)
|
||||
}
|
||||
|
||||
redirectUrl := "/"
|
||||
|
||||
var validCode, validRecoveryCode bool
|
||||
if validCode, err = userTotp.ValidateCode(dto.Code); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot validate TOTP code", err)
|
||||
}
|
||||
if !validCode {
|
||||
validRecoveryCode, err = userTotp.ValidateRecoveryCode(dto.Code)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot validate TOTP code", err)
|
||||
}
|
||||
|
||||
if !validRecoveryCode {
|
||||
ctx.AddFlash(ctx.Tr("auth.totp.invalid-code"), "error")
|
||||
return ctx.RedirectTo("/mfa")
|
||||
}
|
||||
|
||||
ctx.AddFlash(ctx.Tr("auth.totp.code-used", dto.Code), "warning")
|
||||
redirectUrl = "/settings"
|
||||
}
|
||||
|
||||
sess.Values["user"] = userId
|
||||
sess.Options.MaxAge = 60 * 60 * 24 * 365 // 1 year
|
||||
delete(sess.Values, "mfaID")
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
return ctx.RedirectTo(redirectUrl)
|
||||
}
|
||||
|
||||
func DisableTotp(ctx *context.Context) error {
|
||||
user := ctx.User
|
||||
userTotp, err := db.GetTOTPByUserID(user.ID)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot get TOTP by UID", err)
|
||||
}
|
||||
|
||||
if err = userTotp.Delete(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot delete TOTP", err)
|
||||
}
|
||||
|
||||
ctx.AddFlash(ctx.Tr("auth.totp.disabled"), "success")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
|
||||
func RegenerateTotpRecoveryCodes(ctx *context.Context) error {
|
||||
user := ctx.User
|
||||
userTotp, err := db.GetTOTPByUserID(user.ID)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot get TOTP by UID", err)
|
||||
}
|
||||
|
||||
codes, err := userTotp.GenerateRecoveryCodes()
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot generate recovery codes", err)
|
||||
}
|
||||
|
||||
ctx.SetData("recoveryCodes", codes)
|
||||
return ctx.Html("totp.html")
|
||||
}
|
151
internal/web/handlers/auth/webauthn.go
Normal file
151
internal/web/handlers/auth/webauthn.go
Normal file
@ -0,0 +1,151 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
gojson "encoding/json"
|
||||
"github.com/thomiceli/opengist/internal/auth/webauthn"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
"io"
|
||||
)
|
||||
|
||||
func BeginWebAuthnBinding(ctx *context.Context) error {
|
||||
credsCreation, jsonWaSession, err := webauthn.BeginBinding(ctx.User)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot begin WebAuthn registration", err)
|
||||
}
|
||||
|
||||
sess := ctx.GetSession()
|
||||
sess.Values["webauthn_registration_session"] = jsonWaSession
|
||||
sess.Options.MaxAge = 5 * 60 // 5 minutes
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
return ctx.JSON(200, credsCreation)
|
||||
}
|
||||
|
||||
func FinishWebAuthnBinding(ctx *context.Context) error {
|
||||
sess := ctx.GetSession()
|
||||
jsonWaSession, ok := sess.Values["webauthn_registration_session"].([]byte)
|
||||
if !ok {
|
||||
return ctx.ErrorRes(401, "Cannot get WebAuthn registration session", nil)
|
||||
}
|
||||
|
||||
user := ctx.User
|
||||
|
||||
// extract passkey name from request
|
||||
body, err := io.ReadAll(ctx.Request().Body)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(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 ctx.ErrorRes(400, "Invalid request", err)
|
||||
}
|
||||
passkeyName := dto.PasskeyName
|
||||
if passkeyName == "" {
|
||||
passkeyName = "WebAuthn"
|
||||
}
|
||||
|
||||
waCredential, err := webauthn.FinishBinding(user, jsonWaSession, ctx.Request())
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(403, "Failed binding attempt for passkey", err)
|
||||
}
|
||||
|
||||
if _, err = db.CreateFromCrendential(user.ID, passkeyName, waCredential); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot create WebAuthn credential on database", err)
|
||||
}
|
||||
|
||||
delete(sess.Values, "webauthn_registration_session")
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.passkey-registred", passkeyName), "success")
|
||||
return ctx.Json([]string{"OK"})
|
||||
}
|
||||
|
||||
func BeginWebAuthnLogin(ctx *context.Context) error {
|
||||
credsCreation, jsonWaSession, err := webauthn.BeginDiscoverableLogin()
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(401, "Cannot begin WebAuthn login", err)
|
||||
}
|
||||
|
||||
sess := ctx.GetSession()
|
||||
sess.Values["webauthn_login_session"] = jsonWaSession
|
||||
sess.Options.MaxAge = 5 * 60 // 5 minutes
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
return ctx.Json(credsCreation)
|
||||
}
|
||||
|
||||
func FinishWebAuthnLogin(ctx *context.Context) error {
|
||||
sess := ctx.GetSession()
|
||||
sessionData, ok := sess.Values["webauthn_login_session"].([]byte)
|
||||
if !ok {
|
||||
return ctx.ErrorRes(401, "Cannot get WebAuthn login session", nil)
|
||||
}
|
||||
|
||||
userID, err := webauthn.FinishDiscoverableLogin(sessionData, ctx.Request())
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(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")
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
return ctx.Json([]string{"OK"})
|
||||
}
|
||||
|
||||
func BeginWebAuthnAssertion(ctx *context.Context) error {
|
||||
sess := ctx.GetSession()
|
||||
|
||||
ogUser, err := db.GetUserById(sess.Values["mfaID"].(uint))
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot get user", err)
|
||||
}
|
||||
|
||||
credsCreation, jsonWaSession, err := webauthn.BeginLogin(ogUser)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(401, "Cannot begin WebAuthn login", err)
|
||||
}
|
||||
|
||||
sess.Values["webauthn_assertion_session"] = jsonWaSession
|
||||
sess.Options.MaxAge = 5 * 60 // 5 minutes
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
return ctx.Json(credsCreation)
|
||||
}
|
||||
|
||||
func FinishWebAuthnAssertion(ctx *context.Context) error {
|
||||
sess := ctx.GetSession()
|
||||
sessionData, ok := sess.Values["webauthn_assertion_session"].([]byte)
|
||||
if !ok {
|
||||
return ctx.ErrorRes(401, "Cannot get WebAuthn assertion session", nil)
|
||||
}
|
||||
|
||||
userId := sess.Values["mfaID"].(uint)
|
||||
|
||||
ogUser, err := db.GetUserById(userId)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot get user", err)
|
||||
}
|
||||
|
||||
if err = webauthn.FinishLogin(ogUser, sessionData, ctx.Request()); err != nil {
|
||||
return ctx.ErrorRes(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")
|
||||
ctx.SaveSession(sess)
|
||||
|
||||
return ctx.Json([]string{"OK"})
|
||||
}
|
Reference in New Issue
Block a user