otp.go 5.3 KB

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