user.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/usememos/memos/api"
  10. "github.com/usememos/memos/common"
  11. "github.com/labstack/echo/v4"
  12. "golang.org/x/crypto/bcrypt"
  13. )
  14. func (s *Server) registerUserRoutes(g *echo.Group) {
  15. g.POST("/user", func(c echo.Context) error {
  16. ctx := c.Request().Context()
  17. userID, ok := c.Get(getUserIDContextKey()).(int)
  18. if !ok {
  19. return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
  20. }
  21. currentUser, err := s.Store.FindUser(ctx, &api.UserFind{
  22. ID: &userID,
  23. })
  24. if err != nil {
  25. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user by id").SetInternal(err)
  26. }
  27. if currentUser.Role != api.Host {
  28. return echo.NewHTTPError(http.StatusUnauthorized, "Only Host user can create member")
  29. }
  30. userCreate := &api.UserCreate{}
  31. if err := json.NewDecoder(c.Request().Body).Decode(userCreate); err != nil {
  32. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post user request").SetInternal(err)
  33. }
  34. if userCreate.Role == api.Host {
  35. return echo.NewHTTPError(http.StatusForbidden, "Could not create host user")
  36. }
  37. userCreate.OpenID = common.GenUUID()
  38. if err := userCreate.Validate(); err != nil {
  39. return echo.NewHTTPError(http.StatusBadRequest, "Invalid user create format").SetInternal(err)
  40. }
  41. passwordHash, err := bcrypt.GenerateFromPassword([]byte(userCreate.Password), bcrypt.DefaultCost)
  42. if err != nil {
  43. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
  44. }
  45. userCreate.PasswordHash = string(passwordHash)
  46. user, err := s.Store.CreateUser(ctx, userCreate)
  47. if err != nil {
  48. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create user").SetInternal(err)
  49. }
  50. if err := s.createUserCreateActivity(c, user); err != nil {
  51. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
  52. }
  53. return c.JSON(http.StatusOK, composeResponse(user))
  54. })
  55. g.GET("/user", func(c echo.Context) error {
  56. ctx := c.Request().Context()
  57. userList, err := s.Store.FindUserList(ctx, &api.UserFind{})
  58. if err != nil {
  59. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch user list").SetInternal(err)
  60. }
  61. for _, user := range userList {
  62. // data desensitize
  63. user.OpenID = ""
  64. user.Email = ""
  65. }
  66. return c.JSON(http.StatusOK, composeResponse(userList))
  67. })
  68. g.POST("/user/setting", func(c echo.Context) error {
  69. ctx := c.Request().Context()
  70. userID, ok := c.Get(getUserIDContextKey()).(int)
  71. if !ok {
  72. return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
  73. }
  74. userSettingUpsert := &api.UserSettingUpsert{}
  75. if err := json.NewDecoder(c.Request().Body).Decode(userSettingUpsert); err != nil {
  76. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post user setting upsert request").SetInternal(err)
  77. }
  78. if err := userSettingUpsert.Validate(); err != nil {
  79. return echo.NewHTTPError(http.StatusBadRequest, "Invalid user setting format").SetInternal(err)
  80. }
  81. userSettingUpsert.UserID = userID
  82. userSetting, err := s.Store.UpsertUserSetting(ctx, userSettingUpsert)
  83. if err != nil {
  84. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert user setting").SetInternal(err)
  85. }
  86. return c.JSON(http.StatusOK, composeResponse(userSetting))
  87. })
  88. // GET /api/user/me is used to check if the user is logged in.
  89. g.GET("/user/me", func(c echo.Context) error {
  90. ctx := c.Request().Context()
  91. userID, ok := c.Get(getUserIDContextKey()).(int)
  92. if !ok {
  93. return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
  94. }
  95. userFind := &api.UserFind{
  96. ID: &userID,
  97. }
  98. user, err := s.Store.FindUser(ctx, userFind)
  99. if err != nil {
  100. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
  101. }
  102. userSettingList, err := s.Store.FindUserSettingList(ctx, &api.UserSettingFind{
  103. UserID: userID,
  104. })
  105. if err != nil {
  106. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find userSettingList").SetInternal(err)
  107. }
  108. user.UserSettingList = userSettingList
  109. return c.JSON(http.StatusOK, composeResponse(user))
  110. })
  111. g.GET("/user/:id", func(c echo.Context) error {
  112. ctx := c.Request().Context()
  113. id, err := strconv.Atoi(c.Param("id"))
  114. if err != nil {
  115. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted user id").SetInternal(err)
  116. }
  117. user, err := s.Store.FindUser(ctx, &api.UserFind{
  118. ID: &id,
  119. })
  120. if err != nil {
  121. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch user").SetInternal(err)
  122. }
  123. if user != nil {
  124. // data desensitize
  125. user.OpenID = ""
  126. user.Email = ""
  127. }
  128. return c.JSON(http.StatusOK, composeResponse(user))
  129. })
  130. g.PATCH("/user/:id", func(c echo.Context) error {
  131. ctx := c.Request().Context()
  132. userID, err := strconv.Atoi(c.Param("id"))
  133. if err != nil {
  134. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
  135. }
  136. currentUserID, ok := c.Get(getUserIDContextKey()).(int)
  137. if !ok {
  138. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  139. }
  140. currentUser, err := s.Store.FindUser(ctx, &api.UserFind{
  141. ID: &currentUserID,
  142. })
  143. if err != nil {
  144. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
  145. }
  146. if currentUser == nil {
  147. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Current session user not found with ID: %d", currentUserID)).SetInternal(err)
  148. } else if currentUser.Role != api.Host && currentUserID != userID {
  149. return echo.NewHTTPError(http.StatusForbidden, "Access forbidden for current session user").SetInternal(err)
  150. }
  151. currentTs := time.Now().Unix()
  152. userPatch := &api.UserPatch{
  153. UpdatedTs: &currentTs,
  154. }
  155. if err := json.NewDecoder(c.Request().Body).Decode(userPatch); err != nil {
  156. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch user request").SetInternal(err)
  157. }
  158. userPatch.ID = userID
  159. if userPatch.Password != nil && *userPatch.Password != "" {
  160. passwordHash, err := bcrypt.GenerateFromPassword([]byte(*userPatch.Password), bcrypt.DefaultCost)
  161. if err != nil {
  162. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
  163. }
  164. passwordHashStr := string(passwordHash)
  165. userPatch.PasswordHash = &passwordHashStr
  166. }
  167. if userPatch.ResetOpenID != nil && *userPatch.ResetOpenID {
  168. openID := common.GenUUID()
  169. userPatch.OpenID = &openID
  170. }
  171. if err := userPatch.Validate(); err != nil {
  172. return echo.NewHTTPError(http.StatusBadRequest, "Invalid user patch format").SetInternal(err)
  173. }
  174. user, err := s.Store.PatchUser(ctx, userPatch)
  175. if err != nil {
  176. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to patch user").SetInternal(err)
  177. }
  178. userSettingList, err := s.Store.FindUserSettingList(ctx, &api.UserSettingFind{
  179. UserID: userID,
  180. })
  181. if err != nil {
  182. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find userSettingList").SetInternal(err)
  183. }
  184. user.UserSettingList = userSettingList
  185. return c.JSON(http.StatusOK, composeResponse(user))
  186. })
  187. g.DELETE("/user/:id", func(c echo.Context) error {
  188. ctx := c.Request().Context()
  189. currentUserID, ok := c.Get(getUserIDContextKey()).(int)
  190. if !ok {
  191. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  192. }
  193. currentUser, err := s.Store.FindUser(ctx, &api.UserFind{
  194. ID: &currentUserID,
  195. })
  196. if err != nil {
  197. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
  198. }
  199. if currentUser == nil {
  200. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Current session user not found with ID: %d", currentUserID)).SetInternal(err)
  201. } else if currentUser.Role != api.Host {
  202. return echo.NewHTTPError(http.StatusForbidden, "Access forbidden for current session user").SetInternal(err)
  203. }
  204. userID, err := strconv.Atoi(c.Param("id"))
  205. if err != nil {
  206. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
  207. }
  208. userDelete := &api.UserDelete{
  209. ID: userID,
  210. }
  211. if err := s.Store.DeleteUser(ctx, userDelete); err != nil {
  212. if common.ErrorCode(err) == common.NotFound {
  213. return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("User ID not found: %d", userID))
  214. }
  215. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to delete user").SetInternal(err)
  216. }
  217. return c.JSON(http.StatusOK, true)
  218. })
  219. }
  220. func (s *Server) createUserCreateActivity(c echo.Context, user *api.User) error {
  221. ctx := c.Request().Context()
  222. payload := api.ActivityUserCreatePayload{
  223. UserID: user.ID,
  224. Username: user.Username,
  225. Role: user.Role,
  226. }
  227. payloadBytes, err := json.Marshal(payload)
  228. if err != nil {
  229. return errors.Wrap(err, "failed to marshal activity payload")
  230. }
  231. activity, err := s.Store.CreateActivity(ctx, &api.ActivityCreate{
  232. CreatorID: user.ID,
  233. Type: api.ActivityUserCreate,
  234. Level: api.ActivityInfo,
  235. Payload: string(payloadBytes),
  236. })
  237. if err != nil || activity == nil {
  238. return errors.Wrap(err, "failed to create activity")
  239. }
  240. return err
  241. }