auth.go 10.0 KB

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