user.go 17 KB

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