memos/server/user.go

274 lines
9.2 KiB
Go
Raw Normal View History

2022-02-03 10:32:03 +03:00
package server
import (
"encoding/json"
2022-05-02 21:05:43 +03:00
"fmt"
2022-02-03 10:32:03 +03:00
"net/http"
2022-05-19 13:32:04 +03:00
"strconv"
"time"
2022-02-03 10:32:03 +03:00
2023-01-02 18:18:12 +03:00
"github.com/pkg/errors"
2022-06-27 17:09:06 +03:00
"github.com/usememos/memos/api"
"github.com/usememos/memos/common"
2022-02-03 10:32:03 +03:00
"github.com/labstack/echo/v4"
2022-02-06 11:19:20 +03:00
"golang.org/x/crypto/bcrypt"
2022-02-03 10:32:03 +03:00
)
func (s *Server) registerUserRoutes(g *echo.Group) {
g.POST("/user", func(c echo.Context) error {
2022-08-07 04:23:46 +03:00
ctx := c.Request().Context()
2022-08-20 16:03:15 +03:00
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
}
currentUser, err := s.Store.FindUser(ctx, &api.UserFind{
ID: &userID,
})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user by id").SetInternal(err)
}
if currentUser.Role != api.Host {
2022-12-28 15:22:52 +03:00
return echo.NewHTTPError(http.StatusUnauthorized, "Only Host user can create member")
2022-08-20 16:03:15 +03:00
}
2022-12-28 15:22:52 +03:00
userCreate := &api.UserCreate{}
if err := json.NewDecoder(c.Request().Body).Decode(userCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post user request").SetInternal(err)
}
2022-12-28 15:22:52 +03:00
if userCreate.Role == api.Host {
return echo.NewHTTPError(http.StatusForbidden, "Could not create host user")
}
userCreate.OpenID = common.GenUUID()
2022-08-20 16:03:15 +03:00
if err := userCreate.Validate(); err != nil {
2022-12-28 15:22:52 +03:00
return echo.NewHTTPError(http.StatusBadRequest, "Invalid user create format").SetInternal(err)
2022-08-20 16:03:15 +03:00
}
passwordHash, err := bcrypt.GenerateFromPassword([]byte(userCreate.Password), bcrypt.DefaultCost)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
}
userCreate.PasswordHash = string(passwordHash)
2022-08-07 04:23:46 +03:00
user, err := s.Store.CreateUser(ctx, userCreate)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create user").SetInternal(err)
}
2023-01-02 18:18:12 +03:00
if err := s.createUserCreateActivity(c, user); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
}
return c.JSON(http.StatusOK, composeResponse(user))
})
g.GET("/user", func(c echo.Context) error {
2022-08-07 04:23:46 +03:00
ctx := c.Request().Context()
userList, err := s.Store.FindUserList(ctx, &api.UserFind{})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch user list").SetInternal(err)
}
2022-07-26 16:41:20 +03:00
for _, user := range userList {
// data desensitize
user.OpenID = ""
2022-12-28 15:22:52 +03:00
user.Email = ""
2022-07-26 16:41:20 +03:00
}
return c.JSON(http.StatusOK, composeResponse(userList))
})
2023-02-11 10:15:56 +03:00
g.POST("/user/setting", func(c echo.Context) error {
2022-08-07 04:23:46 +03:00
ctx := c.Request().Context()
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
}
2023-02-11 10:15:56 +03:00
userSettingUpsert := &api.UserSettingUpsert{}
if err := json.NewDecoder(c.Request().Body).Decode(userSettingUpsert); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post user setting upsert request").SetInternal(err)
}
2023-02-11 10:15:56 +03:00
if err := userSettingUpsert.Validate(); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Invalid user setting format").SetInternal(err)
}
2023-02-11 10:15:56 +03:00
userSettingUpsert.UserID = userID
userSetting, err := s.Store.UpsertUserSetting(ctx, userSettingUpsert)
if err != nil {
2023-02-11 10:15:56 +03:00
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert user setting").SetInternal(err)
2022-07-09 16:01:09 +03:00
}
return c.JSON(http.StatusOK, composeResponse(userSetting))
})
2023-02-11 10:15:56 +03:00
// GET /api/user/me is used to check if the user is logged in.
g.GET("/user/me", func(c echo.Context) error {
2022-08-07 04:23:46 +03:00
ctx := c.Request().Context()
2022-07-27 14:45:37 +03:00
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
2022-05-02 21:05:43 +03:00
return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
2022-02-04 13:54:24 +03:00
}
2023-02-11 10:15:56 +03:00
userFind := &api.UserFind{
ID: &userID,
2022-02-03 10:32:03 +03:00
}
2023-02-11 10:15:56 +03:00
user, err := s.Store.FindUser(ctx, userFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
}
2023-02-11 10:15:56 +03:00
userSettingList, err := s.Store.FindUserSettingList(ctx, &api.UserSettingFind{
UserID: userID,
})
if err != nil {
2023-02-11 10:15:56 +03:00
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find userSettingList").SetInternal(err)
}
2023-02-11 10:15:56 +03:00
user.UserSettingList = userSettingList
return c.JSON(http.StatusOK, composeResponse(user))
})
g.GET("/user/:id", func(c echo.Context) error {
ctx := c.Request().Context()
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted user id").SetInternal(err)
}
user, err := s.Store.FindUser(ctx, &api.UserFind{
ID: &id,
})
2022-02-03 10:32:03 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch user").SetInternal(err)
}
if user != nil {
// data desensitize
user.OpenID = ""
2022-12-28 15:22:52 +03:00
user.Email = ""
}
return c.JSON(http.StatusOK, composeResponse(user))
})
2022-02-18 17:21:10 +03:00
2022-07-26 17:32:26 +03:00
g.PATCH("/user/:id", func(c echo.Context) error {
2022-08-07 04:23:46 +03:00
ctx := c.Request().Context()
2022-07-26 17:32:26 +03:00
userID, err := strconv.Atoi(c.Param("id"))
2022-02-03 10:32:03 +03:00
if err != nil {
2022-07-26 17:32:26 +03:00
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
2022-02-03 10:32:03 +03:00
}
2022-07-28 15:09:25 +03:00
currentUserID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
2022-08-07 04:23:46 +03:00
currentUser, err := s.Store.FindUser(ctx, &api.UserFind{
2022-05-19 13:32:04 +03:00
ID: &currentUserID,
})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
}
if currentUser == nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Current session user not found with ID: %d", currentUserID)).SetInternal(err)
2022-07-26 17:32:26 +03:00
} else if currentUser.Role != api.Host && currentUserID != userID {
2022-05-19 13:32:04 +03:00
return echo.NewHTTPError(http.StatusForbidden, "Access forbidden for current session user").SetInternal(err)
}
currentTs := time.Now().Unix()
2022-05-19 13:32:04 +03:00
userPatch := &api.UserPatch{
UpdatedTs: &currentTs,
2022-05-19 13:32:04 +03:00
}
if err := json.NewDecoder(c.Request().Body).Decode(userPatch); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch user request").SetInternal(err)
}
2022-12-28 15:22:52 +03:00
userPatch.ID = userID
2022-08-20 16:51:28 +03:00
2022-05-19 13:32:04 +03:00
if userPatch.Password != nil && *userPatch.Password != "" {
passwordHash, err := bcrypt.GenerateFromPassword([]byte(*userPatch.Password), bcrypt.DefaultCost)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
}
passwordHashStr := string(passwordHash)
userPatch.PasswordHash = &passwordHashStr
}
2022-07-26 17:32:26 +03:00
if userPatch.ResetOpenID != nil && *userPatch.ResetOpenID {
openID := common.GenUUID()
userPatch.OpenID = &openID
}
if err := userPatch.Validate(); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Invalid user patch format").SetInternal(err)
}
2022-08-07 04:23:46 +03:00
user, err := s.Store.PatchUser(ctx, userPatch)
2022-05-19 13:32:04 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to patch user").SetInternal(err)
}
userSettingList, err := s.Store.FindUserSettingList(ctx, &api.UserSettingFind{
UserID: userID,
})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find userSettingList").SetInternal(err)
}
user.UserSettingList = userSettingList
return c.JSON(http.StatusOK, composeResponse(user))
2022-05-19 13:32:04 +03:00
})
2022-07-26 17:32:26 +03:00
g.DELETE("/user/:id", func(c echo.Context) error {
2022-08-07 04:23:46 +03:00
ctx := c.Request().Context()
2022-07-28 15:09:25 +03:00
currentUserID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
2022-08-07 04:23:46 +03:00
currentUser, err := s.Store.FindUser(ctx, &api.UserFind{
ID: &currentUserID,
})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user").SetInternal(err)
}
if currentUser == nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Current session user not found with ID: %d", currentUserID)).SetInternal(err)
} else if currentUser.Role != api.Host {
return echo.NewHTTPError(http.StatusForbidden, "Access forbidden for current session user").SetInternal(err)
}
2022-07-26 17:32:26 +03:00
userID, err := strconv.Atoi(c.Param("id"))
if err != nil {
2022-07-26 17:32:26 +03:00
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
}
userDelete := &api.UserDelete{
ID: userID,
}
2022-08-07 04:23:46 +03:00
if err := s.Store.DeleteUser(ctx, userDelete); err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("User ID not found: %d", userID))
}
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to delete user").SetInternal(err)
}
return c.JSON(http.StatusOK, true)
})
2022-02-03 10:32:03 +03:00
}
2023-01-02 18:18:12 +03:00
func (s *Server) createUserCreateActivity(c echo.Context, user *api.User) error {
ctx := c.Request().Context()
payload := api.ActivityUserCreatePayload{
UserID: user.ID,
Username: user.Username,
Role: user.Role,
}
payloadBytes, err := json.Marshal(payload)
2023-01-02 18:18:12 +03:00
if err != nil {
return errors.Wrap(err, "failed to marshal activity payload")
}
2023-01-05 15:56:50 +03:00
activity, err := s.Store.CreateActivity(ctx, &api.ActivityCreate{
2023-01-02 18:18:12 +03:00
CreatorID: user.ID,
Type: api.ActivityUserCreate,
Level: api.ActivityInfo,
Payload: string(payloadBytes),
2023-01-02 18:18:12 +03:00
})
2023-01-07 06:49:58 +03:00
if err != nil || activity == nil {
return errors.Wrap(err, "failed to create activity")
}
2023-01-02 18:18:12 +03:00
return err
}