handler.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package user
  2. import (
  3. "fmt"
  4. "net/http"
  5. . "prime/basic"
  6. "strings"
  7. "github.com/gin-gonic/gin"
  8. "github.com/google/uuid"
  9. )
  10. type UserForm struct {
  11. Username string `json:"username" binding:"required"`
  12. Password string `json:"password" binding:"required"`
  13. }
  14. var Authorized *gin.RouterGroup
  15. func init() {
  16. r := R()
  17. r.POST("/token", func(c *gin.Context) {
  18. // Parse JSON
  19. var json UserForm
  20. if c.Bind(&json) == nil {
  21. fmt.Printf("%+v\n", json)
  22. token, err := GenToken(json.Username, json.Password)
  23. if err == nil {
  24. fmt.Println(token)
  25. c.JSON(http.StatusOK, gin.H{"token": token})
  26. } else {
  27. c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
  28. }
  29. }
  30. })
  31. r.POST("/user", func(c *gin.Context) {
  32. var json UserForm
  33. if c.Bind(&json) == nil {
  34. user, err := Register(json.Username, json.Password)
  35. if err == nil {
  36. c.JSON(http.StatusOK, gin.H{"uid": user.ID})
  37. } else {
  38. c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
  39. }
  40. }
  41. })
  42. Authorized = r.Group("/", JWTAuthMiddleware())
  43. Authorized.GET("home", homeHandler)
  44. Authorized.POST("message", func(c *gin.Context) {
  45. user := c.MustGet("username").(string)
  46. fmt.Printf("username=%s\n", user)
  47. // Parse JSON
  48. var json struct {
  49. Sender string `json:"sender" binding:"required"`
  50. Receiver string `json:"receiver" binding:"required"`
  51. Message string `json:"message" binding:"required"`
  52. }
  53. if c.Bind(&json) == nil {
  54. fmt.Printf("%+v\n", json)
  55. c.JSON(http.StatusOK, gin.H{})
  56. }
  57. })
  58. Authorized.POST("avatar", func(c *gin.Context) {
  59. uid := c.MustGet("uid").(uint)
  60. fmt.Printf("upload avatar uid=%d\n", uid)
  61. file, err := c.FormFile("file")
  62. if err != nil {
  63. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  64. return
  65. }
  66. filename := file.Filename
  67. pos := strings.LastIndex(filename, ".")
  68. if pos == -1 {
  69. c.JSON(http.StatusBadRequest, gin.H{"error": "filename error"})
  70. return
  71. }
  72. filename = uuid.New().String() + filename[pos:]
  73. if err := c.SaveUploadedFile(file, FileDirPath+filename); err != nil {
  74. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  75. return
  76. }
  77. fmt.Println(filename)
  78. if err := SetAvatar(uid, filename); err != nil {
  79. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  80. return
  81. }
  82. c.JSON(http.StatusOK, gin.H{"filename": filename})
  83. })
  84. Authorized.GET("profile/:name", func(c *gin.Context) {
  85. name := c.Param("name")
  86. // uid, err := strconv.Atoi(c.Param("uid"))
  87. // if err != nil {
  88. // c.JSON(http.StatusBadRequest, gin.H{"status": "bad request", "error": err.Error()})
  89. // return
  90. // }
  91. uid, err := GetUID(name)
  92. if err != nil {
  93. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  94. return
  95. }
  96. if uid == 0 {
  97. c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
  98. return
  99. }
  100. profile, err := GetProfile(uid)
  101. if err != nil {
  102. c.JSON(ErrCode(err), gin.H{"error": err.Error()})
  103. return
  104. }
  105. c.JSON(http.StatusOK, gin.H{"profile": profile})
  106. })
  107. Authorized.GET("file/:filename", func(c *gin.Context) {
  108. // uid := c.MustGet("uid").(uint)
  109. filename := c.Param("filename")
  110. // fmt.Printf("uid(%d) get avatar of id=%d\n", uid, id)
  111. // filename, err := GetAvatar(uint(id))
  112. c.FileAttachment(FileDirPath+filename, filename)
  113. })
  114. }
  115. // JWTAuthMiddleware 基于JWT的认证中间件
  116. func JWTAuthMiddleware() func(c *gin.Context) {
  117. return func(c *gin.Context) {
  118. // 客户端携带Token有三种方式 1.放在请求头 2.放在请求体 3.放在URI
  119. // 这里假设Token放在Header的Authorization中,并使用Bearer开头
  120. // 这里的具体实现方式要依据你的实际业务情况决定
  121. authHeader := c.Request.Header.Get("Authorization")
  122. // fmt.Println(authHeader)
  123. if authHeader == "" {
  124. c.JSON(http.StatusBadRequest, gin.H{
  125. "error": "请求头中auth为空",
  126. })
  127. c.Abort()
  128. return
  129. }
  130. // 按空格分割
  131. parts := strings.SplitN(authHeader, " ", 2)
  132. if !(len(parts) == 2 && parts[0] == "Bearer") {
  133. c.JSON(http.StatusBadRequest, gin.H{
  134. "error": "请求头中auth格式有误",
  135. })
  136. c.Abort()
  137. return
  138. }
  139. // parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它
  140. mc, err := ParseToken(parts[1])
  141. fmt.Printf("token=%+v\n", mc)
  142. if err != nil {
  143. c.JSON(http.StatusUnauthorized, gin.H{
  144. "error": "无效的Token",
  145. })
  146. c.Abort()
  147. return
  148. }
  149. // 将当前请求的username信息保存到请求的上下文c上
  150. c.Set("username", mc.Username)
  151. c.Set("uid", mc.UID)
  152. fmt.Printf("username=%s uid=%d\n", mc.Username, mc.UID)
  153. c.Next() // 后续的处理函数可以用过c.Get("uid")来获取当前请求的用户信息
  154. }
  155. }
  156. func homeHandler(c *gin.Context) {
  157. username := c.MustGet("username").(string)
  158. uid := c.MustGet("uid").(uint)
  159. c.JSON(http.StatusOK, gin.H{
  160. "username": username,
  161. "uid": uid,
  162. })
  163. }