otp.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. package user
  2. import (
  3. "bytes"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "fmt"
  8. "github.com/0xJacky/Nginx-UI/api"
  9. "github.com/0xJacky/Nginx-UI/internal/crypto"
  10. "github.com/0xJacky/Nginx-UI/internal/user"
  11. "github.com/0xJacky/Nginx-UI/query"
  12. "github.com/0xJacky/Nginx-UI/settings"
  13. "github.com/gin-gonic/gin"
  14. "github.com/pquerna/otp"
  15. "github.com/pquerna/otp/totp"
  16. "image/jpeg"
  17. "net/http"
  18. "strings"
  19. )
  20. func GenerateTOTP(c *gin.Context) {
  21. user := api.CurrentUser(c)
  22. issuer := fmt.Sprintf("Nginx UI %s", settings.ServerSettings.Name)
  23. issuer = strings.TrimSpace(issuer)
  24. otpOpts := totp.GenerateOpts{
  25. Issuer: issuer,
  26. AccountName: user.Name,
  27. Period: 30, // seconds
  28. Digits: otp.DigitsSix,
  29. Algorithm: otp.AlgorithmSHA1,
  30. }
  31. otpKey, err := totp.Generate(otpOpts)
  32. if err != nil {
  33. api.ErrHandler(c, err)
  34. return
  35. }
  36. ciphertext, err := crypto.AesEncrypt([]byte(otpKey.Secret()))
  37. if err != nil {
  38. api.ErrHandler(c, err)
  39. return
  40. }
  41. qrCode, err := otpKey.Image(512, 512)
  42. if err != nil {
  43. api.ErrHandler(c, err)
  44. return
  45. }
  46. // Encode the image to a buffer
  47. var buf []byte
  48. buffer := bytes.NewBuffer(buf)
  49. err = jpeg.Encode(buffer, qrCode, nil)
  50. if err != nil {
  51. fmt.Println("Error encoding image:", err)
  52. return
  53. }
  54. // Convert the buffer to a base64 string
  55. base64Str := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(buffer.Bytes())
  56. c.JSON(http.StatusOK, gin.H{
  57. "secret": base64.StdEncoding.EncodeToString(ciphertext),
  58. "qr_code": base64Str,
  59. })
  60. }
  61. func EnrollTOTP(c *gin.Context) {
  62. cUser := api.CurrentUser(c)
  63. if cUser.EnabledOTP() {
  64. c.JSON(http.StatusBadRequest, gin.H{
  65. "message": "User already enrolled",
  66. })
  67. return
  68. }
  69. var json struct {
  70. Secret string `json:"secret" binding:"required"`
  71. Passcode string `json:"passcode" binding:"required"`
  72. }
  73. if !api.BindAndValid(c, &json) {
  74. return
  75. }
  76. secret, err := base64.StdEncoding.DecodeString(json.Secret)
  77. if err != nil {
  78. api.ErrHandler(c, err)
  79. return
  80. }
  81. decrypted, err := crypto.AesDecrypt(secret)
  82. if err != nil {
  83. api.ErrHandler(c, err)
  84. return
  85. }
  86. if ok := totp.Validate(json.Passcode, string(decrypted)); !ok {
  87. c.JSON(http.StatusNotAcceptable, gin.H{
  88. "message": "Invalid passcode",
  89. })
  90. return
  91. }
  92. ciphertext, err := crypto.AesEncrypt(decrypted)
  93. if err != nil {
  94. api.ErrHandler(c, err)
  95. return
  96. }
  97. u := query.Auth
  98. _, err = u.Where(u.ID.Eq(cUser.ID)).Update(u.OTPSecret, ciphertext)
  99. if err != nil {
  100. api.ErrHandler(c, err)
  101. return
  102. }
  103. recoveryCode := sha1.Sum(ciphertext)
  104. c.JSON(http.StatusOK, gin.H{
  105. "message": "ok",
  106. "recovery_code": hex.EncodeToString(recoveryCode[:]),
  107. })
  108. }
  109. func ResetOTP(c *gin.Context) {
  110. var json struct {
  111. RecoveryCode string `json:"recovery_code"`
  112. }
  113. if !api.BindAndValid(c, &json) {
  114. return
  115. }
  116. recoverCode, err := hex.DecodeString(json.RecoveryCode)
  117. if err != nil {
  118. api.ErrHandler(c, err)
  119. return
  120. }
  121. cUser := api.CurrentUser(c)
  122. k := sha1.Sum(cUser.OTPSecret)
  123. if !bytes.Equal(k[:], recoverCode) {
  124. c.JSON(http.StatusBadRequest, gin.H{
  125. "message": "Invalid recovery code",
  126. })
  127. return
  128. }
  129. u := query.Auth
  130. _, err = u.Where(u.ID.Eq(cUser.ID)).UpdateSimple(u.OTPSecret.Null())
  131. if err != nil {
  132. api.ErrHandler(c, err)
  133. return
  134. }
  135. c.JSON(http.StatusOK, gin.H{
  136. "message": "ok",
  137. })
  138. }
  139. func OTPStatus(c *gin.Context) {
  140. c.JSON(http.StatusOK, gin.H{
  141. "status": len(api.CurrentUser(c).OTPSecret) > 0,
  142. })
  143. }
  144. func StartSecure2FASession(c *gin.Context) {
  145. var json struct {
  146. OTP string `json:"otp"`
  147. RecoveryCode string `json:"recovery_code"`
  148. }
  149. if !api.BindAndValid(c, &json) {
  150. return
  151. }
  152. u := api.CurrentUser(c)
  153. if !u.EnabledOTP() {
  154. c.JSON(http.StatusBadRequest, gin.H{
  155. "message": "User not configured with 2FA",
  156. })
  157. return
  158. }
  159. if json.OTP == "" && json.RecoveryCode == "" {
  160. c.JSON(http.StatusBadRequest, LoginResponse{
  161. Message: "The user has enabled 2FA",
  162. })
  163. return
  164. }
  165. if err := user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
  166. c.JSON(http.StatusBadRequest, LoginResponse{
  167. Message: "Invalid 2FA or recovery code",
  168. })
  169. return
  170. }
  171. sessionId := user.SetSecureSessionID(u.ID)
  172. c.JSON(http.StatusOK, gin.H{
  173. "session_id": sessionId,
  174. })
  175. }