auth.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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) {
  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 = setUserSession(c, user); err != nil {
  41. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to set signin session").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 = setUserSession(c, user); err != nil {
  119. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to set signin session").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 := s.createUserAuthSignUpActivity(c, user); err != nil {
  181. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
  182. }
  183. err = setUserSession(c, user)
  184. if err != nil {
  185. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to set signup session").SetInternal(err)
  186. }
  187. return c.JSON(http.StatusOK, composeResponse(user))
  188. })
  189. g.POST("/auth/signout", func(c echo.Context) error {
  190. err := removeUserSession(c)
  191. if err != nil {
  192. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to set sign out session").SetInternal(err)
  193. }
  194. return c.JSON(http.StatusOK, true)
  195. })
  196. }
  197. func (s *Server) createUserAuthSignInActivity(c echo.Context, user *api.User) error {
  198. ctx := c.Request().Context()
  199. payload := api.ActivityUserAuthSignInPayload{
  200. UserID: user.ID,
  201. IP: echo.ExtractIPFromRealIPHeader()(c.Request()),
  202. }
  203. payloadBytes, err := json.Marshal(payload)
  204. if err != nil {
  205. return errors.Wrap(err, "failed to marshal activity payload")
  206. }
  207. activity, err := s.Store.CreateActivity(ctx, &api.ActivityCreate{
  208. CreatorID: user.ID,
  209. Type: api.ActivityUserAuthSignIn,
  210. Level: api.ActivityInfo,
  211. Payload: string(payloadBytes),
  212. })
  213. if err != nil || activity == nil {
  214. return errors.Wrap(err, "failed to create activity")
  215. }
  216. return err
  217. }
  218. func (s *Server) createUserAuthSignUpActivity(c echo.Context, user *api.User) error {
  219. ctx := c.Request().Context()
  220. payload := api.ActivityUserAuthSignUpPayload{
  221. Username: user.Username,
  222. IP: echo.ExtractIPFromRealIPHeader()(c.Request()),
  223. }
  224. payloadBytes, err := json.Marshal(payload)
  225. if err != nil {
  226. return errors.Wrap(err, "failed to marshal activity payload")
  227. }
  228. activity, err := s.Store.CreateActivity(ctx, &api.ActivityCreate{
  229. CreatorID: user.ID,
  230. Type: api.ActivityUserAuthSignUp,
  231. Level: api.ActivityInfo,
  232. Payload: string(payloadBytes),
  233. })
  234. if err != nil || activity == nil {
  235. return errors.Wrap(err, "failed to create activity")
  236. }
  237. return err
  238. }