project_handler.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package api
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strconv"
  6. "github.com/go-chi/chi"
  7. "github.com/porter-dev/porter/api/types"
  8. "github.com/porter-dev/porter/internal/analytics"
  9. "github.com/porter-dev/porter/internal/forms"
  10. "github.com/porter-dev/porter/internal/models"
  11. )
  12. // Enumeration of user API error codes, represented as int64
  13. const (
  14. ErrProjectDecode ErrorCode = iota + 600
  15. ErrProjectValidateFields
  16. ErrProjectDataRead
  17. )
  18. // HandleCreateProject validates a project form entry, converts the project to a gorm
  19. // model, and saves the user to the database
  20. func (app *App) HandleCreateProject(w http.ResponseWriter, r *http.Request) {
  21. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  22. if err != nil {
  23. http.Error(w, err.Error(), http.StatusInternalServerError)
  24. return
  25. }
  26. userID, _ := session.Values["user_id"].(uint)
  27. form := &forms.CreateProjectForm{}
  28. // decode from JSON to form value
  29. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  30. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  31. return
  32. }
  33. // validate the form
  34. if err := app.validator.Struct(form); err != nil {
  35. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  36. return
  37. }
  38. // convert the form to a project model
  39. projModel, err := form.ToProject(app.Repo.Project())
  40. if err != nil {
  41. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  42. return
  43. }
  44. // handle write to the database
  45. projModel, err = app.Repo.Project().CreateProject(projModel)
  46. if err != nil {
  47. app.handleErrorDataWrite(err, w)
  48. return
  49. }
  50. // create a new Role with the user as the admin
  51. _, err = app.Repo.Project().CreateProjectRole(projModel, &models.Role{
  52. Role: types.Role{
  53. UserID: userID,
  54. ProjectID: projModel.ID,
  55. Kind: types.RoleAdmin,
  56. },
  57. })
  58. if err != nil {
  59. app.handleErrorDataWrite(err, w)
  60. return
  61. }
  62. app.AnalyticsClient.Track(analytics.ProjectCreateTrack(&analytics.ProjectCreateTrackOpts{
  63. ProjectScopedTrackOpts: analytics.GetProjectScopedTrackOpts(userID, projModel.ID),
  64. }))
  65. app.Logger.Info().Msgf("New project created: %d", projModel.ID)
  66. w.WriteHeader(http.StatusCreated)
  67. projExt := projModel.ToProjectType()
  68. if err := json.NewEncoder(w).Encode(projExt); err != nil {
  69. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  70. return
  71. }
  72. }
  73. // HandleGetProjectRoles lists the roles available to the project. For now, these
  74. // roles are static.
  75. func (app *App) HandleGetProjectRoles(w http.ResponseWriter, r *http.Request) {
  76. roles := []string{models.RoleAdmin, models.RoleDeveloper, models.RoleViewer}
  77. w.WriteHeader(http.StatusOK)
  78. if err := json.NewEncoder(w).Encode(&roles); err != nil {
  79. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  80. return
  81. }
  82. }
  83. type Collaborator struct {
  84. ID uint `json:"id"`
  85. Kind string `json:"kind"`
  86. UserID uint `json:"user_id"`
  87. Email string `json:"email"`
  88. ProjectID uint `json:"project_id"`
  89. }
  90. // HandleListProjectCollaborators lists the collaborators in the project
  91. func (app *App) HandleListProjectCollaborators(w http.ResponseWriter, r *http.Request) {
  92. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  93. if err != nil || id == 0 {
  94. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  95. return
  96. }
  97. roles, err := app.Repo.Project().ListProjectRoles(uint(id))
  98. if err != nil {
  99. app.handleErrorRead(err, ErrProjectDataRead, w)
  100. return
  101. }
  102. res := make([]*Collaborator, 0)
  103. roleMap := make(map[uint]*models.Role)
  104. idArr := make([]uint, 0)
  105. for _, role := range roles {
  106. roleCp := role
  107. roleMap[role.UserID] = &roleCp
  108. idArr = append(idArr, role.UserID)
  109. }
  110. users, err := app.Repo.User().ListUsersByIDs(idArr)
  111. if err != nil {
  112. app.handleErrorRead(err, ErrProjectDataRead, w)
  113. return
  114. }
  115. for _, user := range users {
  116. res = append(res, &Collaborator{
  117. ID: roleMap[user.ID].ID,
  118. Kind: string(roleMap[user.ID].Kind),
  119. UserID: roleMap[user.ID].UserID,
  120. Email: user.Email,
  121. ProjectID: roleMap[user.ID].ProjectID,
  122. })
  123. }
  124. w.WriteHeader(http.StatusOK)
  125. if err := json.NewEncoder(w).Encode(res); err != nil {
  126. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  127. return
  128. }
  129. }
  130. // HandleReadProject returns an externalized Project (models.ProjectExternal)
  131. // based on an ID
  132. func (app *App) HandleReadProject(w http.ResponseWriter, r *http.Request) {
  133. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  134. if err != nil || id == 0 {
  135. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  136. return
  137. }
  138. proj, err := app.Repo.Project().ReadProject(uint(id))
  139. if err != nil {
  140. app.handleErrorRead(err, ErrProjectDataRead, w)
  141. return
  142. }
  143. projExt := proj.ToProjectType()
  144. w.WriteHeader(http.StatusOK)
  145. if err := json.NewEncoder(w).Encode(projExt); err != nil {
  146. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  147. return
  148. }
  149. }
  150. // HandleReadProjectPolicy returns the policy document given the current user
  151. func (app *App) HandleReadProjectPolicy(w http.ResponseWriter, r *http.Request) {
  152. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  153. if err != nil || id == 0 {
  154. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  155. return
  156. }
  157. userID, err := app.getUserIDFromRequest(r)
  158. if err != nil {
  159. app.handleErrorInternal(err, w)
  160. return
  161. }
  162. role, err := app.Repo.Project().ReadProjectRole(uint(id), userID)
  163. if err != nil {
  164. app.handleErrorRead(err, ErrProjectDataRead, w)
  165. return
  166. }
  167. // case on the role to get the policy document
  168. var policy types.Policy
  169. switch role.Kind {
  170. case types.RoleAdmin:
  171. policy = types.AdminPolicy
  172. case types.RoleDeveloper:
  173. policy = types.DeveloperPolicy
  174. case types.RoleViewer:
  175. policy = types.ViewerPolicy
  176. }
  177. if err := json.NewEncoder(w).Encode(policy); err != nil {
  178. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  179. return
  180. }
  181. }
  182. // HandleUpdateProjectRole updates a project role with a new "kind"
  183. func (app *App) HandleUpdateProjectRole(w http.ResponseWriter, r *http.Request) {
  184. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  185. if err != nil || id == 0 {
  186. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  187. return
  188. }
  189. userID, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  190. if err != nil || id == 0 {
  191. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  192. return
  193. }
  194. role, err := app.Repo.Project().ReadProjectRole(uint(id), uint(userID))
  195. if err != nil {
  196. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  197. return
  198. }
  199. form := &forms.UpdateProjectRoleForm{}
  200. // decode from JSON to form value
  201. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  202. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  203. return
  204. }
  205. role.Kind = types.RoleKind(form.Kind)
  206. role, err = app.Repo.Project().UpdateProjectRole(uint(id), role)
  207. if err != nil {
  208. app.handleErrorRead(err, ErrProjectDataRead, w)
  209. return
  210. }
  211. if err := json.NewEncoder(w).Encode(role.Externalize()); err != nil {
  212. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  213. return
  214. }
  215. }
  216. // HandleDeleteProject deletes a project from the db, reading from the project_id
  217. // in the URL param
  218. func (app *App) HandleDeleteProject(w http.ResponseWriter, r *http.Request) {
  219. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  220. if err != nil || id == 0 {
  221. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  222. return
  223. }
  224. proj, err := app.Repo.Project().ReadProject(uint(id))
  225. if err != nil {
  226. app.handleErrorRead(err, ErrProjectDataRead, w)
  227. return
  228. }
  229. proj, err = app.Repo.Project().DeleteProject(proj)
  230. if err != nil {
  231. app.handleErrorRead(err, ErrProjectDataRead, w)
  232. return
  233. }
  234. projExternal := proj.ToProjectType()
  235. w.WriteHeader(http.StatusOK)
  236. if err := json.NewEncoder(w).Encode(projExternal); err != nil {
  237. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  238. return
  239. }
  240. }
  241. // HandleDeleteProjectRole deletes a project role from the db, reading from the project_id
  242. // in the URL param
  243. func (app *App) HandleDeleteProjectRole(w http.ResponseWriter, r *http.Request) {
  244. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  245. if err != nil || id == 0 {
  246. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  247. return
  248. }
  249. userID, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  250. if err != nil || id == 0 {
  251. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  252. return
  253. }
  254. role, err := app.Repo.Project().ReadProjectRole(uint(id), uint(userID))
  255. if err != nil {
  256. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  257. return
  258. }
  259. role, err = app.Repo.Project().DeleteProjectRole(uint(id), uint(userID))
  260. if err != nil {
  261. app.handleErrorRead(err, ErrProjectDataRead, w)
  262. return
  263. }
  264. if err := json.NewEncoder(w).Encode(role.Externalize()); err != nil {
  265. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  266. return
  267. }
  268. }