ExtractOrganizationParam grabs an organization from the "organization" URL parameter. This middleware requires the API key middleware higher in the call stack for authentication.
(db database.Store)
| 52 | // ExtractOrganizationParam grabs an organization from the "organization" URL parameter. |
| 53 | // This middleware requires the API key middleware higher in the call stack for authentication. |
| 54 | func ExtractOrganizationParam(db database.Store) func(http.Handler) http.Handler { |
| 55 | return func(next http.Handler) http.Handler { |
| 56 | return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 57 | ctx := r.Context() |
| 58 | arg := chi.URLParam(r, "organization") |
| 59 | if arg == "" { |
| 60 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 61 | Message: "\"organization\" must be provided.", |
| 62 | }) |
| 63 | return |
| 64 | } |
| 65 | |
| 66 | var organization database.Organization |
| 67 | var dbErr error |
| 68 | |
| 69 | // If the name is exactly "default", then we fetch the default |
| 70 | // organization. This is a special case to make it easier |
| 71 | // for single org deployments. |
| 72 | // |
| 73 | // arg == uuid.Nil.String() should be a temporary workaround for |
| 74 | // legacy provisioners that don't provide an organization ID. |
| 75 | // This prevents a breaking change. |
| 76 | // TODO: This change was added March 2024. Nil uuid returning the |
| 77 | // default org should be removed some number of months after |
| 78 | // that date. |
| 79 | if arg == codersdk.DefaultOrganization || arg == uuid.Nil.String() { |
| 80 | organization, dbErr = db.GetDefaultOrganization(ctx) |
| 81 | } else { |
| 82 | // Try by name or uuid. |
| 83 | id, err := uuid.Parse(arg) |
| 84 | if err == nil { |
| 85 | organization, dbErr = db.GetOrganizationByID(ctx, id) |
| 86 | } else { |
| 87 | organization, dbErr = db.GetOrganizationByName(ctx, database.GetOrganizationByNameParams{ |
| 88 | Name: arg, |
| 89 | Deleted: false, |
| 90 | }) |
| 91 | } |
| 92 | } |
| 93 | if httpapi.Is404Error(dbErr) { |
| 94 | httpapi.ResourceNotFound(rw) |
| 95 | return |
| 96 | } |
| 97 | if dbErr != nil { |
| 98 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 99 | Message: fmt.Sprintf("Internal error fetching organization %q.", arg), |
| 100 | Detail: dbErr.Error(), |
| 101 | }) |
| 102 | return |
| 103 | } |
| 104 | ctx = context.WithValue(ctx, organizationParamContextKey{}, organization) |
| 105 | next.ServeHTTP(rw, r.WithContext(ctx)) |
| 106 | }) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | // OrganizationMember is the database object plus the Username and Avatar URL. Including these |
| 111 | // in the middleware is preferable to a join at the SQL layer so that we can keep the |