auth.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "regexp"
  7. "github.com/pkg/errors"
  8. "github.com/usememos/memos/api"
  9. "github.com/usememos/memos/common"
  10. "github.com/usememos/memos/plugin/idp"
  11. "github.com/usememos/memos/plugin/idp/oauth2"
  12. "github.com/usememos/memos/store"
  13. "github.com/labstack/echo/v4"
  14. "golang.org/x/crypto/bcrypt"
  15. )
  16. func (s *Server) registerAuthRoutes(g *echo.Group, secret string) {
  17. g.POST("/auth/signin", func(c echo.Context) error {
  18. ctx := c.Request().Context()
  19. signin := &api.SignIn{}
  20. if err := json.NewDecoder(c.Request().Body).Decode(signin); err != nil {
  21. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted signin request").SetInternal(err)
  22. }
  23. userFind := &api.UserFind{
  24. Username: &signin.Username,
  25. }
  26. user, err := s.Store.FindUser(ctx, userFind)
  27. if err != nil && common.ErrorCode(err) != common.NotFound {
  28. return echo.NewHTTPError(http.StatusInternalServerError, "Incorrect login credentials, please try again")
  29. }
  30. if user == nil {
  31. return echo.NewHTTPError(http.StatusUnauthorized, "Incorrect login credentials, please try again")
  32. } else if user.RowStatus == api.Archived {
  33. return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("User has been archived with username %s", signin.Username))
  34. }
  35. // Compare the stored hashed password, with the hashed version of the password that was received.
  36. if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(signin.Password)); err != nil {
  37. // If the two passwords don't match, return a 401 status.
  38. return echo.NewHTTPError(http.StatusUnauthorized, "Incorrect login credentials, please try again")
  39. }
  40. if err := GenerateTokensAndSetCookies(c, user, s.Profile.Mode, secret); err != nil {
  41. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate tokens").SetInternal(err)
  42. }
  43. if err := s.createUserAuthSignInActivity(c, user); err != nil {
  44. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
  45. }
  46. return c.JSON(http.StatusOK, composeResponse(user))
  47. })
  48. g.POST("/auth/signin/sso", func(c echo.Context) error {
  49. ctx := c.Request().Context()
  50. signin := &api.SSOSignIn{}
  51. if err := json.NewDecoder(c.Request().Body).Decode(signin); err != nil {
  52. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted signin request").SetInternal(err)
  53. }
  54. identityProviderMessage, err := s.Store.GetIdentityProvider(ctx, &store.FindIdentityProviderMessage{
  55. ID: &signin.IdentityProviderID,
  56. })
  57. if err != nil {
  58. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find identity provider").SetInternal(err)
  59. }
  60. var userInfo *idp.IdentityProviderUserInfo
  61. if identityProviderMessage.Type == store.IdentityProviderOAuth2 {
  62. oauth2IdentityProvider, err := oauth2.NewIdentityProvider(identityProviderMessage.Config.OAuth2Config)
  63. if err != nil {
  64. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create identity provider instance").SetInternal(err)
  65. }
  66. token, err := oauth2IdentityProvider.ExchangeToken(ctx, signin.RedirectURI, signin.Code)
  67. if err != nil {
  68. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to exchange token").SetInternal(err)
  69. }
  70. userInfo, err = oauth2IdentityProvider.UserInfo(token)
  71. if err != nil {
  72. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get user info").SetInternal(err)
  73. }
  74. }
  75. identifierFilter := identityProviderMessage.IdentifierFilter
  76. if identifierFilter != "" {
  77. identifierFilterRegex, err := regexp.Compile(identifierFilter)
  78. if err != nil {
  79. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to compile identifier filter").SetInternal(err)
  80. }
  81. if !identifierFilterRegex.MatchString(userInfo.Identifier) {
  82. return echo.NewHTTPError(http.StatusUnauthorized, "Access denied, identifier does not match the filter.").SetInternal(err)
  83. }
  84. }
  85. user, err := s.Store.FindUser(ctx, &api.UserFind{
  86. Username: &userInfo.Identifier,
  87. })
  88. if err != nil && common.ErrorCode(err) != common.NotFound {
  89. return echo.NewHTTPError(http.StatusInternalServerError, "Incorrect login credentials, please try again")
  90. }
  91. if user == nil {
  92. userCreate := &api.UserCreate{
  93. Username: userInfo.Identifier,
  94. // The new signup user should be normal user by default.
  95. Role: api.NormalUser,
  96. Nickname: userInfo.DisplayName,
  97. Email: userInfo.Email,
  98. Password: userInfo.Email,
  99. OpenID: common.GenUUID(),
  100. }
  101. password, err := common.RandomString(20)
  102. if err != nil {
  103. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate random password").SetInternal(err)
  104. }
  105. passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  106. if err != nil {
  107. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
  108. }
  109. userCreate.PasswordHash = string(passwordHash)
  110. user, err = s.Store.CreateUser(ctx, userCreate)
  111. if err != nil {
  112. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create user").SetInternal(err)
  113. }
  114. }
  115. if user.RowStatus == api.Archived {
  116. return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("User has been archived with username %s", userInfo.Identifier))
  117. }
  118. if err := GenerateTokensAndSetCookies(c, user, s.Profile.Mode, secret); err != nil {
  119. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate tokens").SetInternal(err)
  120. }
  121. if err := s.createUserAuthSignInActivity(c, user); err != nil {
  122. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
  123. }
  124. return c.JSON(http.StatusOK, composeResponse(user))
  125. })
  126. g.POST("/auth/signup", func(c echo.Context) error {
  127. ctx := c.Request().Context()
  128. signup := &api.SignUp{}
  129. if err := json.NewDecoder(c.Request().Body).Decode(signup); err != nil {
  130. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted signup request").SetInternal(err)
  131. }
  132. userCreate := &api.UserCreate{
  133. Username: signup.Username,
  134. // The new signup user should be normal user by default.
  135. Role: api.NormalUser,
  136. Nickname: signup.Username,
  137. Password: signup.Password,
  138. OpenID: common.GenUUID(),
  139. }
  140. hostUserType := api.Host
  141. existedHostUsers, err := s.Store.FindUserList(ctx, &api.UserFind{
  142. Role: &hostUserType,
  143. })
  144. if err != nil {
  145. return echo.NewHTTPError(http.StatusBadRequest, "Failed to find users").SetInternal(err)
  146. }
  147. if len(existedHostUsers) == 0 {
  148. // Change the default role to host if there is no host user.
  149. userCreate.Role = api.Host
  150. } else {
  151. allowSignUpSetting, err := s.Store.FindSystemSetting(ctx, &api.SystemSettingFind{
  152. Name: api.SystemSettingAllowSignUpName,
  153. })
  154. if err != nil && common.ErrorCode(err) != common.NotFound {
  155. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find system setting").SetInternal(err)
  156. }
  157. allowSignUpSettingValue := false
  158. if allowSignUpSetting != nil {
  159. err = json.Unmarshal([]byte(allowSignUpSetting.Value), &allowSignUpSettingValue)
  160. if err != nil {
  161. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to unmarshal system setting allow signup").SetInternal(err)
  162. }
  163. }
  164. if !allowSignUpSettingValue {
  165. return echo.NewHTTPError(http.StatusUnauthorized, "signup is disabled").SetInternal(err)
  166. }
  167. }
  168. if err := userCreate.Validate(); err != nil {
  169. return echo.NewHTTPError(http.StatusBadRequest, "Invalid user create format").SetInternal(err)
  170. }
  171. passwordHash, err := bcrypt.GenerateFromPassword([]byte(signup.Password), bcrypt.DefaultCost)
  172. if err != nil {
  173. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
  174. }
  175. userCreate.PasswordHash = string(passwordHash)
  176. user, err := s.Store.CreateUser(ctx, userCreate)
  177. if err != nil {
  178. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create user").SetInternal(err)
  179. }
  180. if err := GenerateTokensAndSetCookies(c, user, s.Profile.Mode, secret); err != nil {
  181. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate tokens").SetInternal(err)
  182. }
  183. if err := s.createUserAuthSignUpActivity(c, user); err != nil {
  184. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
  185. }
  186. return c.JSON(http.StatusOK, composeResponse(user))
  187. })
  188. g.POST("/auth/signout", func(c echo.Context) error {
  189. RemoveTokensAndCookies(c)
  190. return c.JSON(http.StatusOK, true)
  191. })
  192. }
  193. func (s *Server) createUserAuthSignInActivity(c echo.Context, user *api.User) error {
  194. ctx := c.Request().Context()
  195. payload := api.ActivityUserAuthSignInPayload{
  196. UserID: user.ID,
  197. IP: echo.ExtractIPFromRealIPHeader()(c.Request()),
  198. }
  199. payloadBytes, err := json.Marshal(payload)
  200. if err != nil {
  201. return errors.Wrap(err, "failed to marshal activity payload")
  202. }
  203. activity, err := s.Store.CreateActivity(ctx, &api.ActivityCreate{
  204. CreatorID: user.ID,
  205. Type: api.ActivityUserAuthSignIn,
  206. Level: api.ActivityInfo,
  207. Payload: string(payloadBytes),
  208. })
  209. if err != nil || activity == nil {
  210. return errors.Wrap(err, "failed to create activity")
  211. }
  212. return err
  213. }
  214. func (s *Server) createUserAuthSignUpActivity(c echo.Context, user *api.User) error {
  215. ctx := c.Request().Context()
  216. payload := api.ActivityUserAuthSignUpPayload{
  217. Username: user.Username,
  218. IP: echo.ExtractIPFromRealIPHeader()(c.Request()),
  219. }
  220. payloadBytes, err := json.Marshal(payload)
  221. if err != nil {
  222. return errors.Wrap(err, "failed to marshal activity payload")
  223. }
  224. activity, err := s.Store.CreateActivity(ctx, &api.ActivityCreate{
  225. CreatorID: user.ID,
  226. Type: api.ActivityUserAuthSignUp,
  227. Level: api.ActivityInfo,
  228. Payload: string(payloadBytes),
  229. })
  230. if err != nil || activity == nil {
  231. return errors.Wrap(err, "failed to create activity")
  232. }
  233. return err
  234. }