user.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. package v1
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/labstack/echo/v4"
  9. "github.com/pkg/errors"
  10. "golang.org/x/crypto/bcrypt"
  11. "github.com/usememos/memos/internal/util"
  12. "github.com/usememos/memos/server/service/metric"
  13. "github.com/usememos/memos/store"
  14. )
  15. // Role is the type of a role.
  16. type Role string
  17. const (
  18. // RoleHost is the HOST role.
  19. RoleHost Role = "HOST"
  20. // RoleAdmin is the ADMIN role.
  21. RoleAdmin Role = "ADMIN"
  22. // RoleUser is the USER role.
  23. RoleUser Role = "USER"
  24. )
  25. func (role Role) String() string {
  26. return string(role)
  27. }
  28. type User struct {
  29. ID int32 `json:"id"`
  30. // Standard fields
  31. RowStatus RowStatus `json:"rowStatus"`
  32. CreatedTs int64 `json:"createdTs"`
  33. UpdatedTs int64 `json:"updatedTs"`
  34. // Domain specific fields
  35. Username string `json:"username"`
  36. Role Role `json:"role"`
  37. Email string `json:"email"`
  38. Nickname string `json:"nickname"`
  39. PasswordHash string `json:"-"`
  40. AvatarURL string `json:"avatarUrl"`
  41. }
  42. type CreateUserRequest struct {
  43. Username string `json:"username"`
  44. Role Role `json:"role"`
  45. Email string `json:"email"`
  46. Nickname string `json:"nickname"`
  47. Password string `json:"password"`
  48. }
  49. type UpdateUserRequest struct {
  50. RowStatus *RowStatus `json:"rowStatus"`
  51. Username *string `json:"username"`
  52. Email *string `json:"email"`
  53. Nickname *string `json:"nickname"`
  54. Password *string `json:"password"`
  55. AvatarURL *string `json:"avatarUrl"`
  56. }
  57. func (s *APIV1Service) registerUserRoutes(g *echo.Group) {
  58. g.GET("/user", s.GetUserList)
  59. g.POST("/user", s.CreateUser)
  60. g.GET("/user/me", s.GetCurrentUser)
  61. // NOTE: This should be moved to /api/v2/user/:username
  62. g.GET("/user/name/:username", s.GetUserByUsername)
  63. g.GET("/user/:id", s.GetUserByID)
  64. g.PATCH("/user/:id", s.UpdateUser)
  65. g.DELETE("/user/:id", s.DeleteUser)
  66. }
  67. // GetUserList godoc
  68. //
  69. // @Summary Get a list of users
  70. // @Tags user
  71. // @Produce json
  72. // @Success 200 {object} []store.User "User list"
  73. // @Failure 500 {object} nil "Failed to fetch user list"
  74. // @Router /api/v1/user [GET]
  75. func (s *APIV1Service) GetUserList(c echo.Context) error {
  76. ctx := c.Request().Context()
  77. userID, ok := c.Get(userIDContextKey).(int32)
  78. if !ok {
  79. return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
  80. }
  81. currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
  82. ID: &userID,
  83. })
  84. if err != nil {
  85. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user by id").SetInternal(err)
  86. }
  87. if currentUser == nil {
  88. return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
  89. }
  90. if currentUser.Role != store.RoleHost && currentUser.Role != store.RoleAdmin {
  91. return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized to list users")
  92. }
  93. list, err := s.Store.ListUsers(ctx, &store.FindUser{})
  94. if err != nil {
  95. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch user list").SetInternal(err)
  96. }
  97. userMessageList := make([]*User, 0, len(list))
  98. for _, user := range list {
  99. userMessage := convertUserFromStore(user)
  100. // data desensitize
  101. userMessage.Email = ""
  102. userMessageList = append(userMessageList, userMessage)
  103. }
  104. return c.JSON(http.StatusOK, userMessageList)
  105. }
  106. // CreateUser godoc
  107. //
  108. // @Summary Create a user
  109. // @Tags user
  110. // @Accept json
  111. // @Produce json
  112. // @Param body body CreateUserRequest true "Request object"
  113. // @Success 200 {object} store.User "Created user"
  114. // @Failure 400 {object} nil "Malformatted post user request | Invalid user create format"
  115. // @Failure 401 {object} nil "Missing auth session | Unauthorized to create user"
  116. // @Failure 403 {object} nil "Could not create host user"
  117. // @Failure 500 {object} nil "Failed to find user by id | Failed to generate password hash | Failed to create user | Failed to create activity"
  118. // @Router /api/v1/user [POST]
  119. func (s *APIV1Service) CreateUser(c echo.Context) error {
  120. ctx := c.Request().Context()
  121. userID, ok := c.Get(userIDContextKey).(int32)
  122. if !ok {
  123. return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
  124. }
  125. currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
  126. ID: &userID,
  127. })
  128. if err != nil {
  129. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user by id").SetInternal(err)
  130. }
  131. if currentUser == nil {
  132. return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
  133. }
  134. if currentUser.Role != store.RoleHost {
  135. return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized to create user")
  136. }
  137. userCreate := &CreateUserRequest{}
  138. if err := json.NewDecoder(c.Request().Body).Decode(userCreate); err != nil {
  139. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post user request").SetInternal(err)
  140. }
  141. if err := userCreate.Validate(); err != nil {
  142. return echo.NewHTTPError(http.StatusBadRequest, "Invalid user create format").SetInternal(err)
  143. }
  144. if !util.ResourceNameMatcher.MatchString(strings.ToLower(userCreate.Username)) {
  145. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid username %s", userCreate.Username)).SetInternal(err)
  146. }
  147. // Disallow host user to be created.
  148. if userCreate.Role == RoleHost {
  149. return echo.NewHTTPError(http.StatusForbidden, "Could not create host user")
  150. }
  151. passwordHash, err := bcrypt.GenerateFromPassword([]byte(userCreate.Password), bcrypt.DefaultCost)
  152. if err != nil {
  153. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
  154. }
  155. user, err := s.Store.CreateUser(ctx, &store.User{
  156. Username: userCreate.Username,
  157. Role: store.Role(userCreate.Role),
  158. Email: userCreate.Email,
  159. Nickname: userCreate.Nickname,
  160. PasswordHash: string(passwordHash),
  161. })
  162. if err != nil {
  163. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create user").SetInternal(err)
  164. }
  165. userMessage := convertUserFromStore(user)
  166. metric.Enqueue("user create")
  167. return c.JSON(http.StatusOK, userMessage)
  168. }
  169. // GetCurrentUser godoc
  170. //
  171. // @Summary Get current user
  172. // @Tags user
  173. // @Produce json
  174. // @Success 200 {object} store.User "Current user"
  175. // @Failure 401 {object} nil "Missing auth session"
  176. // @Failure 500 {object} nil "Failed to find user | Failed to find userSettingList"
  177. // @Router /api/v1/user/me [GET]
  178. func (s *APIV1Service) GetCurrentUser(c echo.Context) error {
  179. ctx := c.Request().Context()
  180. userID, ok := c.Get(userIDContextKey).(int32)
  181. if !ok {
  182. return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
  183. }
  184. user, err := s.Store.GetUser(ctx, &store.FindUser{ID: &userID})
  185. if err != nil {
  186. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
  187. }
  188. if user == nil {
  189. return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
  190. }
  191. userMessage := convertUserFromStore(user)
  192. return c.JSON(http.StatusOK, userMessage)
  193. }
  194. // GetUserByUsername godoc
  195. //
  196. // @Summary Get user by username
  197. // @Tags user
  198. // @Produce json
  199. // @Param username path string true "Username"
  200. // @Success 200 {object} store.User "Requested user"
  201. // @Failure 404 {object} nil "User not found"
  202. // @Failure 500 {object} nil "Failed to find user"
  203. // @Router /api/v1/user/name/{username} [GET]
  204. func (s *APIV1Service) GetUserByUsername(c echo.Context) error {
  205. ctx := c.Request().Context()
  206. username := c.Param("username")
  207. user, err := s.Store.GetUser(ctx, &store.FindUser{Username: &username})
  208. if err != nil {
  209. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
  210. }
  211. if user == nil {
  212. return echo.NewHTTPError(http.StatusNotFound, "User not found")
  213. }
  214. userMessage := convertUserFromStore(user)
  215. // data desensitize
  216. userMessage.Email = ""
  217. return c.JSON(http.StatusOK, userMessage)
  218. }
  219. // GetUserByID godoc
  220. //
  221. // @Summary Get user by id
  222. // @Tags user
  223. // @Produce json
  224. // @Param id path int true "User ID"
  225. // @Success 200 {object} store.User "Requested user"
  226. // @Failure 400 {object} nil "Malformatted user id"
  227. // @Failure 404 {object} nil "User not found"
  228. // @Failure 500 {object} nil "Failed to find user"
  229. // @Router /api/v1/user/{id} [GET]
  230. func (s *APIV1Service) GetUserByID(c echo.Context) error {
  231. ctx := c.Request().Context()
  232. id, err := util.ConvertStringToInt32(c.Param("id"))
  233. if err != nil {
  234. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted user id").SetInternal(err)
  235. }
  236. user, err := s.Store.GetUser(ctx, &store.FindUser{ID: &id})
  237. if err != nil {
  238. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
  239. }
  240. if user == nil {
  241. return echo.NewHTTPError(http.StatusNotFound, "User not found")
  242. }
  243. userMessage := convertUserFromStore(user)
  244. userID, ok := c.Get(userIDContextKey).(int32)
  245. if !ok || userID != user.ID {
  246. // Data desensitize.
  247. userMessage.Email = ""
  248. }
  249. return c.JSON(http.StatusOK, userMessage)
  250. }
  251. // DeleteUser godoc
  252. //
  253. // @Summary Delete a user
  254. // @Tags user
  255. // @Produce json
  256. // @Param id path string true "User ID"
  257. // @Success 200 {boolean} true "User deleted"
  258. // @Failure 400 {object} nil "ID is not a number: %s | Current session user not found with ID: %d"
  259. // @Failure 401 {object} nil "Missing user in session"
  260. // @Failure 403 {object} nil "Unauthorized to delete user"
  261. // @Failure 500 {object} nil "Failed to find user | Failed to delete user"
  262. // @Router /api/v1/user/{id} [DELETE]
  263. func (s *APIV1Service) DeleteUser(c echo.Context) error {
  264. ctx := c.Request().Context()
  265. currentUserID, ok := c.Get(userIDContextKey).(int32)
  266. if !ok {
  267. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  268. }
  269. currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
  270. ID: &currentUserID,
  271. })
  272. if err != nil {
  273. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
  274. }
  275. if currentUser == nil {
  276. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Current session user not found with ID: %d", currentUserID)).SetInternal(err)
  277. } else if currentUser.Role != store.RoleHost {
  278. return echo.NewHTTPError(http.StatusForbidden, "Unauthorized to delete user").SetInternal(err)
  279. }
  280. userID, err := util.ConvertStringToInt32(c.Param("id"))
  281. if err != nil {
  282. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
  283. }
  284. if currentUserID == userID {
  285. return echo.NewHTTPError(http.StatusBadRequest, "Cannot delete current user")
  286. }
  287. if err := s.Store.DeleteUser(ctx, &store.DeleteUser{
  288. ID: userID,
  289. }); err != nil {
  290. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to delete user").SetInternal(err)
  291. }
  292. return c.JSON(http.StatusOK, true)
  293. }
  294. // UpdateUser godoc
  295. //
  296. // @Summary Update a user
  297. // @Tags user
  298. // @Produce json
  299. // @Param id path string true "User ID"
  300. // @Param patch body UpdateUserRequest true "Patch request"
  301. // @Success 200 {object} store.User "Updated user"
  302. // @Failure 400 {object} nil "ID is not a number: %s | Current session user not found with ID: %d | Malformatted patch user request | Invalid update user request"
  303. // @Failure 401 {object} nil "Missing user in session"
  304. // @Failure 403 {object} nil "Unauthorized to update user"
  305. // @Failure 500 {object} nil "Failed to find user | Failed to generate password hash | Failed to patch user | Failed to find userSettingList"
  306. // @Router /api/v1/user/{id} [PATCH]
  307. func (s *APIV1Service) UpdateUser(c echo.Context) error {
  308. ctx := c.Request().Context()
  309. userID, err := util.ConvertStringToInt32(c.Param("id"))
  310. if err != nil {
  311. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
  312. }
  313. currentUserID, ok := c.Get(userIDContextKey).(int32)
  314. if !ok {
  315. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  316. }
  317. currentUser, err := s.Store.GetUser(ctx, &store.FindUser{ID: &currentUserID})
  318. if err != nil {
  319. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
  320. }
  321. if currentUser == nil {
  322. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Current session user not found with ID: %d", currentUserID)).SetInternal(err)
  323. } else if currentUser.Role != store.RoleHost && currentUserID != userID {
  324. return echo.NewHTTPError(http.StatusForbidden, "Unauthorized to update user").SetInternal(err)
  325. }
  326. request := &UpdateUserRequest{}
  327. if err := json.NewDecoder(c.Request().Body).Decode(request); err != nil {
  328. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch user request").SetInternal(err)
  329. }
  330. if err := request.Validate(); err != nil {
  331. return echo.NewHTTPError(http.StatusBadRequest, "Invalid update user request").SetInternal(err)
  332. }
  333. currentTs := time.Now().Unix()
  334. userUpdate := &store.UpdateUser{
  335. ID: userID,
  336. UpdatedTs: &currentTs,
  337. }
  338. if request.RowStatus != nil {
  339. rowStatus := store.RowStatus(request.RowStatus.String())
  340. userUpdate.RowStatus = &rowStatus
  341. if rowStatus == store.Archived && currentUserID == userID {
  342. return echo.NewHTTPError(http.StatusBadRequest, "Cannot archive current user")
  343. }
  344. }
  345. if request.Username != nil {
  346. if !util.ResourceNameMatcher.MatchString(strings.ToLower(*request.Username)) {
  347. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid username %s", *request.Username)).SetInternal(err)
  348. }
  349. userUpdate.Username = request.Username
  350. }
  351. if request.Email != nil {
  352. userUpdate.Email = request.Email
  353. }
  354. if request.Nickname != nil {
  355. userUpdate.Nickname = request.Nickname
  356. }
  357. if request.Password != nil {
  358. passwordHash, err := bcrypt.GenerateFromPassword([]byte(*request.Password), bcrypt.DefaultCost)
  359. if err != nil {
  360. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
  361. }
  362. passwordHashStr := string(passwordHash)
  363. userUpdate.PasswordHash = &passwordHashStr
  364. }
  365. if request.AvatarURL != nil {
  366. userUpdate.AvatarURL = request.AvatarURL
  367. }
  368. user, err := s.Store.UpdateUser(ctx, userUpdate)
  369. if err != nil {
  370. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to patch user").SetInternal(err)
  371. }
  372. userMessage := convertUserFromStore(user)
  373. return c.JSON(http.StatusOK, userMessage)
  374. }
  375. func (create CreateUserRequest) Validate() error {
  376. if len(create.Username) < 3 {
  377. return errors.New("username is too short, minimum length is 3")
  378. }
  379. if len(create.Username) > 32 {
  380. return errors.New("username is too long, maximum length is 32")
  381. }
  382. if len(create.Password) < 3 {
  383. return errors.New("password is too short, minimum length is 3")
  384. }
  385. if len(create.Password) > 512 {
  386. return errors.New("password is too long, maximum length is 512")
  387. }
  388. if len(create.Nickname) > 64 {
  389. return errors.New("nickname is too long, maximum length is 64")
  390. }
  391. if create.Email != "" {
  392. if len(create.Email) > 256 {
  393. return errors.New("email is too long, maximum length is 256")
  394. }
  395. if !util.ValidateEmail(create.Email) {
  396. return errors.New("invalid email format")
  397. }
  398. }
  399. return nil
  400. }
  401. func (update UpdateUserRequest) Validate() error {
  402. if update.Username != nil && len(*update.Username) < 3 {
  403. return errors.New("username is too short, minimum length is 3")
  404. }
  405. if update.Username != nil && len(*update.Username) > 32 {
  406. return errors.New("username is too long, maximum length is 32")
  407. }
  408. if update.Password != nil && len(*update.Password) < 3 {
  409. return errors.New("password is too short, minimum length is 3")
  410. }
  411. if update.Password != nil && len(*update.Password) > 512 {
  412. return errors.New("password is too long, maximum length is 512")
  413. }
  414. if update.Nickname != nil && len(*update.Nickname) > 64 {
  415. return errors.New("nickname is too long, maximum length is 64")
  416. }
  417. if update.AvatarURL != nil {
  418. if len(*update.AvatarURL) > 2<<20 {
  419. return errors.New("avatar is too large, maximum is 2MB")
  420. }
  421. }
  422. if update.Email != nil && *update.Email != "" {
  423. if len(*update.Email) > 256 {
  424. return errors.New("email is too long, maximum length is 256")
  425. }
  426. if !util.ValidateEmail(*update.Email) {
  427. return errors.New("invalid email format")
  428. }
  429. }
  430. return nil
  431. }
  432. func convertUserFromStore(user *store.User) *User {
  433. return &User{
  434. ID: user.ID,
  435. RowStatus: RowStatus(user.RowStatus),
  436. CreatedTs: user.CreatedTs,
  437. UpdatedTs: user.UpdatedTs,
  438. Username: user.Username,
  439. Role: Role(user.Role),
  440. Email: user.Email,
  441. Nickname: user.Nickname,
  442. PasswordHash: user.PasswordHash,
  443. AvatarURL: user.AvatarURL,
  444. }
  445. }