MCPcopy Create free account
hub / github.com/chainreactors/EvilProxy / Save

Method Save

internal/store/postgresstore.go:189–269  ·  view source on GitHub ↗

Save persists authentication metadata to disk and PostgreSQL.

(ctx context.Context, auth *cliproxyauth.Auth)

Source from the content-addressed store, hash-verified

187
188// Save persists authentication metadata to disk and PostgreSQL.
189func (s *PostgresStore) Save(ctx context.Context, auth *cliproxyauth.Auth) (string, error) {
190 if auth == nil {
191 return "", fmt.Errorf("postgres store: auth is nil")
192 }
193
194 path, err := s.resolveAuthPath(auth)
195 if err != nil {
196 return "", err
197 }
198 if path == "" {
199 return "", fmt.Errorf("postgres store: missing file path attribute for %s", auth.ID)
200 }
201
202 if auth.Disabled {
203 if _, statErr := os.Stat(path); errors.Is(statErr, fs.ErrNotExist) {
204 return "", nil
205 }
206 }
207
208 s.mu.Lock()
209 defer s.mu.Unlock()
210
211 if err = os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
212 return "", fmt.Errorf("postgres store: create auth directory: %w", err)
213 }
214
215 switch {
216 case auth.Storage != nil:
217 if auth.Metadata == nil {
218 auth.Metadata = make(map[string]any)
219 }
220 auth.Metadata["disabled"] = auth.Disabled
221 if setter, ok := auth.Storage.(interface{ SetMetadata(map[string]any) }); ok {
222 setter.SetMetadata(auth.Metadata)
223 }
224 if err = auth.Storage.SaveTokenToFile(path); err != nil {
225 return "", err
226 }
227 case auth.Metadata != nil:
228 auth.Metadata["disabled"] = auth.Disabled
229 raw, errMarshal := json.Marshal(auth.Metadata)
230 if errMarshal != nil {
231 return "", fmt.Errorf("postgres store: marshal metadata: %w", errMarshal)
232 }
233 if existing, errRead := os.ReadFile(path); errRead == nil {
234 if jsonEqual(existing, raw) {
235 return path, nil
236 }
237 } else if errRead != nil && !errors.Is(errRead, fs.ErrNotExist) {
238 return "", fmt.Errorf("postgres store: read existing metadata: %w", errRead)
239 }
240 tmp := path + ".tmp"
241 if errWrite := os.WriteFile(tmp, raw, 0o600); errWrite != nil {
242 return "", fmt.Errorf("postgres store: write temp auth file: %w", errWrite)
243 }
244 if errRename := os.Rename(tmp, path); errRename != nil {
245 return "", fmt.Errorf("postgres store: rename auth file: %w", errRename)
246 }

Callers

nothing calls this directly

Calls 6

resolveAuthPathMethod · 0.95
relativeAuthIDMethod · 0.95
upsertAuthRecordMethod · 0.95
jsonEqualFunction · 0.70
SetMetadataMethod · 0.65
SaveTokenToFileMethod · 0.65

Tested by

no test coverage detected