mirror of
https://github.com/0xJacky/nginx-ui.git
synced 2025-05-11 02:15:48 +02:00
feat: save settings required 2fa if enabled otp
This commit is contained in:
parent
d0af8bd427
commit
11c733547f
5 changed files with 218 additions and 190 deletions
|
@ -1,13 +1,14 @@
|
||||||
package settings
|
package settings
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/0xJacky/Nginx-UI/internal/middleware"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func InitRouter(r *gin.RouterGroup) {
|
func InitRouter(r *gin.RouterGroup) {
|
||||||
r.GET("settings/server/name", GetServerName)
|
r.GET("settings/server/name", GetServerName)
|
||||||
r.GET("settings", GetSettings)
|
r.GET("settings", GetSettings)
|
||||||
r.POST("settings", SaveSettings)
|
r.POST("settings", middleware.RequireSecureSession(), SaveSettings)
|
||||||
|
|
||||||
r.GET("settings/auth/banned_ips", GetBanLoginIP)
|
r.GET("settings/auth/banned_ips", GetBanLoginIP)
|
||||||
r.DELETE("settings/auth/banned_ip", RemoveBannedIP)
|
r.DELETE("settings/auth/banned_ip", RemoveBannedIP)
|
||||||
|
|
367
api/user/otp.go
367
api/user/otp.go
|
@ -1,215 +1,238 @@
|
||||||
package user
|
package user
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/sha1"
|
"crypto/sha1"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/0xJacky/Nginx-UI/api"
|
"github.com/0xJacky/Nginx-UI/api"
|
||||||
"github.com/0xJacky/Nginx-UI/internal/crypto"
|
"github.com/0xJacky/Nginx-UI/internal/crypto"
|
||||||
"github.com/0xJacky/Nginx-UI/internal/user"
|
"github.com/0xJacky/Nginx-UI/internal/user"
|
||||||
"github.com/0xJacky/Nginx-UI/query"
|
"github.com/0xJacky/Nginx-UI/query"
|
||||||
"github.com/0xJacky/Nginx-UI/settings"
|
"github.com/0xJacky/Nginx-UI/settings"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pquerna/otp"
|
"github.com/pquerna/otp"
|
||||||
"github.com/pquerna/otp/totp"
|
"github.com/pquerna/otp/totp"
|
||||||
"image/jpeg"
|
"image/jpeg"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GenerateTOTP(c *gin.Context) {
|
func GenerateTOTP(c *gin.Context) {
|
||||||
u := api.CurrentUser(c)
|
u := api.CurrentUser(c)
|
||||||
|
|
||||||
issuer := fmt.Sprintf("Nginx UI %s", settings.ServerSettings.Name)
|
issuer := fmt.Sprintf("Nginx UI %s", settings.ServerSettings.Name)
|
||||||
issuer = strings.TrimSpace(issuer)
|
issuer = strings.TrimSpace(issuer)
|
||||||
|
|
||||||
otpOpts := totp.GenerateOpts{
|
otpOpts := totp.GenerateOpts{
|
||||||
Issuer: issuer,
|
Issuer: issuer,
|
||||||
AccountName: u.Name,
|
AccountName: u.Name,
|
||||||
Period: 30, // seconds
|
Period: 30, // seconds
|
||||||
Digits: otp.DigitsSix,
|
Digits: otp.DigitsSix,
|
||||||
Algorithm: otp.AlgorithmSHA1,
|
Algorithm: otp.AlgorithmSHA1,
|
||||||
}
|
}
|
||||||
otpKey, err := totp.Generate(otpOpts)
|
otpKey, err := totp.Generate(otpOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
api.ErrHandler(c, err)
|
api.ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ciphertext, err := crypto.AesEncrypt([]byte(otpKey.Secret()))
|
ciphertext, err := crypto.AesEncrypt([]byte(otpKey.Secret()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
api.ErrHandler(c, err)
|
api.ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
qrCode, err := otpKey.Image(512, 512)
|
qrCode, err := otpKey.Image(512, 512)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
api.ErrHandler(c, err)
|
api.ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Encode the image to a buffer
|
// Encode the image to a buffer
|
||||||
var buf []byte
|
var buf []byte
|
||||||
buffer := bytes.NewBuffer(buf)
|
buffer := bytes.NewBuffer(buf)
|
||||||
err = jpeg.Encode(buffer, qrCode, nil)
|
err = jpeg.Encode(buffer, qrCode, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Error encoding image:", err)
|
fmt.Println("Error encoding image:", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert the buffer to a base64 string
|
// Convert the buffer to a base64 string
|
||||||
base64Str := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(buffer.Bytes())
|
base64Str := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(buffer.Bytes())
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"secret": base64.StdEncoding.EncodeToString(ciphertext),
|
"secret": base64.StdEncoding.EncodeToString(ciphertext),
|
||||||
"qr_code": base64Str,
|
"qr_code": base64Str,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func EnrollTOTP(c *gin.Context) {
|
func EnrollTOTP(c *gin.Context) {
|
||||||
cUser := api.CurrentUser(c)
|
cUser := api.CurrentUser(c)
|
||||||
if cUser.EnabledOTP() {
|
if cUser.EnabledOTP() {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
"message": "User already enrolled",
|
"message": "User already enrolled",
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if settings.ServerSettings.Demo {
|
if settings.ServerSettings.Demo {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
"message": "This feature is disabled in demo mode",
|
"message": "This feature is disabled in demo mode",
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var json struct {
|
var json struct {
|
||||||
Secret string `json:"secret" binding:"required"`
|
Secret string `json:"secret" binding:"required"`
|
||||||
Passcode string `json:"passcode" binding:"required"`
|
Passcode string `json:"passcode" binding:"required"`
|
||||||
}
|
}
|
||||||
if !api.BindAndValid(c, &json) {
|
if !api.BindAndValid(c, &json) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
secret, err := base64.StdEncoding.DecodeString(json.Secret)
|
secret, err := base64.StdEncoding.DecodeString(json.Secret)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
api.ErrHandler(c, err)
|
api.ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
decrypted, err := crypto.AesDecrypt(secret)
|
decrypted, err := crypto.AesDecrypt(secret)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
api.ErrHandler(c, err)
|
api.ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if ok := totp.Validate(json.Passcode, string(decrypted)); !ok {
|
if ok := totp.Validate(json.Passcode, string(decrypted)); !ok {
|
||||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||||
"message": "Invalid passcode",
|
"message": "Invalid passcode",
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ciphertext, err := crypto.AesEncrypt(decrypted)
|
ciphertext, err := crypto.AesEncrypt(decrypted)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
api.ErrHandler(c, err)
|
api.ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
u := query.Auth
|
u := query.Auth
|
||||||
_, err = u.Where(u.ID.Eq(cUser.ID)).Update(u.OTPSecret, ciphertext)
|
_, err = u.Where(u.ID.Eq(cUser.ID)).Update(u.OTPSecret, ciphertext)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
api.ErrHandler(c, err)
|
api.ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
recoveryCode := sha1.Sum(ciphertext)
|
recoveryCode := sha1.Sum(ciphertext)
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"message": "ok",
|
"message": "ok",
|
||||||
"recovery_code": hex.EncodeToString(recoveryCode[:]),
|
"recovery_code": hex.EncodeToString(recoveryCode[:]),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResetOTP(c *gin.Context) {
|
func ResetOTP(c *gin.Context) {
|
||||||
var json struct {
|
var json struct {
|
||||||
RecoveryCode string `json:"recovery_code"`
|
RecoveryCode string `json:"recovery_code"`
|
||||||
}
|
}
|
||||||
if !api.BindAndValid(c, &json) {
|
if !api.BindAndValid(c, &json) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
recoverCode, err := hex.DecodeString(json.RecoveryCode)
|
recoverCode, err := hex.DecodeString(json.RecoveryCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
api.ErrHandler(c, err)
|
api.ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
cUser := api.CurrentUser(c)
|
cUser := api.CurrentUser(c)
|
||||||
k := sha1.Sum(cUser.OTPSecret)
|
k := sha1.Sum(cUser.OTPSecret)
|
||||||
if !bytes.Equal(k[:], recoverCode) {
|
if !bytes.Equal(k[:], recoverCode) {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
"message": "Invalid recovery code",
|
"message": "Invalid recovery code",
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
u := query.Auth
|
u := query.Auth
|
||||||
_, err = u.Where(u.ID.Eq(cUser.ID)).UpdateSimple(u.OTPSecret.Null())
|
_, err = u.Where(u.ID.Eq(cUser.ID)).UpdateSimple(u.OTPSecret.Null())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
api.ErrHandler(c, err)
|
api.ErrHandler(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"message": "ok",
|
"message": "ok",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func OTPStatus(c *gin.Context) {
|
func OTPStatus(c *gin.Context) {
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"status": len(api.CurrentUser(c).OTPSecret) > 0,
|
"status": len(api.CurrentUser(c).OTPSecret) > 0,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func SecureSessionStatus(c *gin.Context) {
|
func SecureSessionStatus(c *gin.Context) {
|
||||||
// if you can visit this endpoint, you are already in a secure session
|
cUser := api.CurrentUser(c)
|
||||||
c.JSON(http.StatusOK, gin.H{
|
if !cUser.EnabledOTP() {
|
||||||
"status": true,
|
c.JSON(http.StatusOK, gin.H{
|
||||||
})
|
"status": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ssid := c.GetHeader("X-Secure-Session-ID")
|
||||||
|
if ssid == "" {
|
||||||
|
ssid = c.Query("X-Secure-Session-ID")
|
||||||
|
}
|
||||||
|
if ssid == "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"status": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if user.VerifySecureSessionID(ssid, cUser.ID) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"status": true,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"status": false,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func StartSecure2FASession(c *gin.Context) {
|
func StartSecure2FASession(c *gin.Context) {
|
||||||
var json struct {
|
var json struct {
|
||||||
OTP string `json:"otp"`
|
OTP string `json:"otp"`
|
||||||
RecoveryCode string `json:"recovery_code"`
|
RecoveryCode string `json:"recovery_code"`
|
||||||
}
|
}
|
||||||
if !api.BindAndValid(c, &json) {
|
if !api.BindAndValid(c, &json) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
u := api.CurrentUser(c)
|
u := api.CurrentUser(c)
|
||||||
if !u.EnabledOTP() {
|
if !u.EnabledOTP() {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
"message": "User not configured with 2FA",
|
"message": "User not configured with 2FA",
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if json.OTP == "" && json.RecoveryCode == "" {
|
if json.OTP == "" && json.RecoveryCode == "" {
|
||||||
c.JSON(http.StatusBadRequest, LoginResponse{
|
c.JSON(http.StatusBadRequest, LoginResponse{
|
||||||
Message: "The user has enabled 2FA",
|
Message: "The user has enabled 2FA",
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
|
if err := user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, LoginResponse{
|
c.JSON(http.StatusBadRequest, LoginResponse{
|
||||||
Message: "Invalid 2FA or recovery code",
|
Message: "Invalid 2FA or recovery code",
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sessionId := user.SetSecureSessionID(u.ID)
|
sessionId := user.SetSecureSessionID(u.ID)
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"session_id": sessionId,
|
"session_id": sessionId,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
package user
|
package user
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/0xJacky/Nginx-UI/internal/middleware"
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -27,7 +26,6 @@ func InitUserRouter(r *gin.RouterGroup) {
|
||||||
r.POST("/otp_enroll", EnrollTOTP)
|
r.POST("/otp_enroll", EnrollTOTP)
|
||||||
r.POST("/otp_reset", ResetOTP)
|
r.POST("/otp_reset", ResetOTP)
|
||||||
|
|
||||||
r.GET("/otp_secure_session_status",
|
r.GET("/otp_secure_session_status", SecureSessionStatus)
|
||||||
middleware.RequireSecureSession(), SecureSessionStatus)
|
|
||||||
r.POST("/otp_secure_session", StartSecure2FASession)
|
r.POST("/otp_secure_session", StartSecure2FASession)
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,6 +23,7 @@ const useOTPModal = () => {
|
||||||
|
|
||||||
const open = async (): Promise<string> => {
|
const open = async (): Promise<string> => {
|
||||||
const { status } = await otp.status()
|
const { status } = await otp.status()
|
||||||
|
const { status: secureSessionStatus } = await otp.secure_session_status()
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
if (!status) {
|
if (!status) {
|
||||||
|
@ -33,13 +34,12 @@ const useOTPModal = () => {
|
||||||
|
|
||||||
const cookies = useCookies(['nginx-ui-2fa'])
|
const cookies = useCookies(['nginx-ui-2fa'])
|
||||||
const ssid = cookies.get('secure_session_id')
|
const ssid = cookies.get('secure_session_id')
|
||||||
if (ssid) {
|
if (ssid && secureSessionStatus) {
|
||||||
resolve(ssid)
|
resolve(ssid)
|
||||||
secureSessionId.value = ssid
|
secureSessionId.value = ssid
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
injectStyles()
|
injectStyles()
|
||||||
let container: HTMLDivElement | null = document.createElement('div')
|
let container: HTMLDivElement | null = document.createElement('div')
|
||||||
document.body.appendChild(container)
|
document.body.appendChild(container)
|
||||||
|
@ -51,11 +51,11 @@ const useOTPModal = () => {
|
||||||
}
|
}
|
||||||
|
|
||||||
const verify = (passcode: string, recovery: string) => {
|
const verify = (passcode: string, recovery: string) => {
|
||||||
otp.start_secure_session(passcode, recovery).then(r => {
|
otp.start_secure_session(passcode, recovery).then(async r => {
|
||||||
cookies.set('secure_session_id', r.session_id, { maxAge: 60 * 3 })
|
cookies.set('secure_session_id', r.session_id, { maxAge: 60 * 3 })
|
||||||
resolve(r.session_id)
|
|
||||||
close()
|
close()
|
||||||
secureSessionId.value = r.session_id
|
secureSessionId.value = r.session_id
|
||||||
|
resolve(r.session_id)
|
||||||
}).catch(async () => {
|
}).catch(async () => {
|
||||||
refOTPAuthorization.value?.clearInput()
|
refOTPAuthorization.value?.clearInput()
|
||||||
await message.error($gettext('Invalid passcode or recovery code'))
|
await message.error($gettext('Invalid passcode or recovery code'))
|
||||||
|
|
|
@ -11,6 +11,7 @@ import type { Settings } from '@/views/preference/typedef'
|
||||||
import LogrotateSettings from '@/views/preference/LogrotateSettings.vue'
|
import LogrotateSettings from '@/views/preference/LogrotateSettings.vue'
|
||||||
import { useSettingsStore } from '@/pinia'
|
import { useSettingsStore } from '@/pinia'
|
||||||
import AuthSettings from '@/views/preference/AuthSettings.vue'
|
import AuthSettings from '@/views/preference/AuthSettings.vue'
|
||||||
|
import useOTPModal from '@/components/OTP/useOTPModal'
|
||||||
|
|
||||||
const data = ref<Settings>({
|
const data = ref<Settings>({
|
||||||
server: {
|
server: {
|
||||||
|
@ -66,16 +67,21 @@ const refAuthSettings = ref()
|
||||||
async function save() {
|
async function save() {
|
||||||
// fix type
|
// fix type
|
||||||
data.value.server.http_challenge_port = data.value.server.http_challenge_port.toString()
|
data.value.server.http_challenge_port = data.value.server.http_challenge_port.toString()
|
||||||
settings.save(data.value).then(r => {
|
|
||||||
if (!settingsStore.is_remote)
|
const otpModal = useOTPModal()
|
||||||
server_name.value = r?.server?.name ?? ''
|
|
||||||
data.value = r
|
otpModal.open().then(() => {
|
||||||
refAuthSettings.value?.getBannedIPs?.()
|
settings.save(data.value).then(r => {
|
||||||
message.success($gettext('Save successfully'))
|
if (!settingsStore.is_remote)
|
||||||
errors.value = {}
|
server_name.value = r?.server?.name ?? ''
|
||||||
}).catch(e => {
|
data.value = r
|
||||||
errors.value = e.errors
|
refAuthSettings.value?.getBannedIPs?.()
|
||||||
message.error(e?.message ?? $gettext('Server error'))
|
message.success($gettext('Save successfully'))
|
||||||
|
errors.value = {}
|
||||||
|
}).catch(e => {
|
||||||
|
errors.value = e.errors
|
||||||
|
message.error(e?.message ?? $gettext('Server error'))
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue