otp.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. u := 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: u.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. if settings.ServerSettings.Demo {
  70. c.JSON(http.StatusBadRequest, gin.H{
  71. "message": "This feature is disabled in demo mode",
  72. })
  73. return
  74. }
  75. var json struct {
  76. Secret string `json:"secret" binding:"required"`
  77. Passcode string `json:"passcode" binding:"required"`
  78. }
  79. if !api.BindAndValid(c, &json) {
  80. return
  81. }
  82. secret, err := base64.StdEncoding.DecodeString(json.Secret)
  83. if err != nil {
  84. api.ErrHandler(c, err)
  85. return
  86. }
  87. decrypted, err := crypto.AesDecrypt(secret)
  88. if err != nil {
  89. api.ErrHandler(c, err)
  90. return
  91. }
  92. if ok := totp.Validate(json.Passcode, string(decrypted)); !ok {
  93. c.JSON(http.StatusNotAcceptable, gin.H{
  94. "message": "Invalid passcode",
  95. })
  96. return
  97. }
  98. ciphertext, err := crypto.AesEncrypt(decrypted)
  99. if err != nil {
  100. api.ErrHandler(c, err)
  101. return
  102. }
  103. u := query.Auth
  104. _, err = u.Where(u.ID.Eq(cUser.ID)).Update(u.OTPSecret, ciphertext)
  105. if err != nil {
  106. api.ErrHandler(c, err)
  107. return
  108. }
  109. recoveryCode := sha1.Sum(ciphertext)
  110. c.JSON(http.StatusOK, gin.H{
  111. "message": "ok",
  112. "recovery_code": hex.EncodeToString(recoveryCode[:]),
  113. })
  114. }
  115. func ResetOTP(c *gin.Context) {
  116. var json struct {
  117. RecoveryCode string `json:"recovery_code"`
  118. }
  119. if !api.BindAndValid(c, &json) {
  120. return
  121. }
  122. recoverCode, err := hex.DecodeString(json.RecoveryCode)
  123. if err != nil {
  124. api.ErrHandler(c, err)
  125. return
  126. }
  127. cUser := api.CurrentUser(c)
  128. k := sha1.Sum(cUser.OTPSecret)
  129. if !bytes.Equal(k[:], recoverCode) {
  130. c.JSON(http.StatusBadRequest, gin.H{
  131. "message": "Invalid recovery code",
  132. })
  133. return
  134. }
  135. u := query.Auth
  136. _, err = u.Where(u.ID.Eq(cUser.ID)).UpdateSimple(u.OTPSecret.Null())
  137. if err != nil {
  138. api.ErrHandler(c, err)
  139. return
  140. }
  141. c.JSON(http.StatusOK, gin.H{
  142. "message": "ok",
  143. })
  144. }
  145. func OTPStatus(c *gin.Context) {
  146. c.JSON(http.StatusOK, gin.H{
  147. "status": len(api.CurrentUser(c).OTPSecret) > 0,
  148. })
  149. }
  150. func StartSecure2FASession(c *gin.Context) {
  151. var json struct {
  152. OTP string `json:"otp"`
  153. RecoveryCode string `json:"recovery_code"`
  154. }
  155. if !api.BindAndValid(c, &json) {
  156. return
  157. }
  158. u := api.CurrentUser(c)
  159. if !u.EnabledOTP() {
  160. c.JSON(http.StatusBadRequest, gin.H{
  161. "message": "User not configured with 2FA",
  162. })
  163. return
  164. }
  165. if json.OTP == "" && json.RecoveryCode == "" {
  166. c.JSON(http.StatusBadRequest, LoginResponse{
  167. Message: "The user has enabled 2FA",
  168. })
  169. return
  170. }
  171. if err := user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
  172. c.JSON(http.StatusBadRequest, LoginResponse{
  173. Message: "Invalid 2FA or recovery code",
  174. })
  175. return
  176. }
  177. sessionId := user.SetSecureSessionID(u.ID)
  178. c.JSON(http.StatusOK, gin.H{
  179. "session_id": sessionId,
  180. })
  181. }