diff --git a/README.md b/README.md index d293bae..89d1c64 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,35 @@ FLOWCV_COOKIE=flowcvsidapp=s%3A... # your session cookie, OR - **Resume id** is optional: with one resume it's auto-selected; with several, set `FLOWCV_RESUME_ID` or pass `--resume-id ` (run `flowcv resumes` to list). +### Multiple accounts and Google sign-in + +FlowCV accounts created through Google do not have a FlowCV password for the +`login` endpoint. Add their existing browser session cookie instead. The prompt +is hidden, so the cookie is not stored in shell history: + +```console +flowcv account add gmail --use +# paste either the flowcvsidapp value or a full Cookie header when prompted +flowcv account add qq +flowcv account list +flowcv account use gmail +flowcv --account qq resumes +``` + +Find `flowcvsidapp` after signing into the desired account in the browser: +DevTools → Application → Cookies → `https://app.flowcv.com`. Each named account +has isolated credentials and session state under the FlowCV CLI config folder. + +To copy a resume between accounts: + +```console +flowcv --account gmail resumes +flowcv transfer --from gmail --to qq --resume-id SOURCE_ID --title "Imported CV" +``` + +The transfer creates a new resume in the destination account and leaves the +source unchanged. FlowCV plan limits still apply. + ## CLI ```bash diff --git a/flowcvcli/cli.py b/flowcvcli/cli.py index 2e6d645..96d9e85 100644 --- a/flowcvcli/cli.py +++ b/flowcvcli/cli.py @@ -15,6 +15,7 @@ """ import argparse import datetime +import getpass import json import os import re @@ -29,7 +30,8 @@ from .api import FlowCV from .client import login as do_login, _write_session, _jar_header from .config import (Config, dotenv_files_found, resolve_auth_source, - session_file_info) + session_file_info, list_accounts, load_account, save_account, + use_account, remove_account, selected_account) from .errors import FlowCVError from .content import SECTION_META, label_of, rich_field from .jsonresume import from_jsonresume, to_jsonresume @@ -110,7 +112,8 @@ def _result(env, label): def _fc(a): - return FlowCV(resume_id=getattr(a, "resume_id_override", None)) + cfg = Config.load(account=getattr(a, "account_override", None)) + return FlowCV(config=cfg, resume_id=getattr(a, "resume_id_override", None)) # ------------------------------------------------------------------ commands @@ -118,10 +121,63 @@ def cmd_login(a): fc = _fc(a) if not (fc.cfg.email and fc.cfg.password): sys.exit("Set FLOWCV_EMAIL and FLOWCV_PASSWORD in .env to use `login`.") - _write_session(_jar_header(do_login(fc.cfg.email, fc.cfg.password))) + _write_session(_jar_header(do_login(fc.cfg.email, fc.cfg.password)), fc.cfg.session_file) _emit({"success": True}, lambda: print("login ok -> session cached to .flowcv_session")) +def cmd_account_add(a): + cookie = getpass.getpass("FlowCV Cookie (hidden; include flowcvsidapp=): ") + path = save_account(a.name, cookie=cookie, resume_id=a.resume_id) + if a.use: + use_account(a.name) + _emit({"success": True, "account": a.name, "selected": bool(a.use)}, + lambda: print(f"saved account {a.name!r} -> {path}" + (" (selected)" if a.use else ""))) + + +def cmd_account_migrate(a): + """Save the currently configured legacy login/session as a named account.""" + cfg = Config.load() + cookie = FlowCV(config=cfg).cookie() + save_account(a.name, cookie=cookie, resume_id=a.resume_id or cfg.resume_id) + if a.use: + use_account(a.name) + _emit({"success": True, "account": a.name, "selected": bool(a.use)}, + lambda: print(f"saved current login as account {a.name!r}" + + (" (selected)" if a.use else ""))) + + +def cmd_account_list(a): + names = list_accounts() + current = selected_account() + rows = [{"name": n, "current": n == current, + "resume_id": load_account(n).get("resume_id")} for n in names] + _emit(rows, lambda: [print(("* " if r["current"] else " ") + r["name"]) + for r in rows]) + + +def cmd_account_use(a): + use_account(a.name) + _emit({"success": True, "account": a.name}, lambda: print(f"using account {a.name!r}")) + + +def cmd_account_remove(a): + remove_account(a.name) + _emit({"success": True, "account": a.name}, lambda: print(f"removed account {a.name!r}")) + + +def cmd_transfer(a): + """Copy a resume between two named accounts without printing its contents.""" + src = FlowCV(config=Config.load(account=a.from_account), + resume_id=getattr(a, "resume_id_override", None)) + dst = FlowCV(config=Config.load(account=a.to_account)) + resume = src.export_resume() + new_id = dst.import_resume(resume, title=a.title) + data = {"success": True, "from": a.from_account, "to": a.to_account, + "source_resume_id": resume.get("id"), "new_resume_id": new_id} + _emit(data, lambda: print(f"copied {resume.get('title') or 'resume'}: " + f"{a.from_account} -> {a.to_account} ({new_id})")) + + def cmd_resumes(a): resumes = _fc(a).list_resumes() @@ -583,8 +639,8 @@ def _doctor_env_cookie_check(cfg): "full name=value pair from DevTools, not just the value") -def _doctor_session_check(): - info = session_file_info() +def _doctor_session_check(cfg=None): + info = session_file_info(cfg.session_file if cfg else None) path = info["path"] if not info["exists"]: return _check("session file", None, f"no cached session ({path})") @@ -620,11 +676,11 @@ def _doctor_live_check(a, offline): def cmd_doctor(a): - cfg = Config.load() + cfg = Config.load(account=getattr(a, "account_override", None)) source = resolve_auth_source(cfg) checks = [_doctor_auth_check(cfg, source), _doctor_env_cookie_check(cfg), - _doctor_session_check(), + _doctor_session_check(cfg), _doctor_curl_cffi_check(source), _doctor_live_check(a, a.offline)] ok = all(c["ok"] is not False for c in checks) # skipped (None) never fails @@ -652,6 +708,8 @@ def build_parser(): # BEFORE the subcommand (same issue as --json; read via getattr). common.add_argument("--resume-id", dest="resume_id_override", default=argparse.SUPPRESS, help="target a specific resume") + common.add_argument("--account", dest="account_override", default=argparse.SUPPRESS, + help="use a named FlowCV account for this command") # default=SUPPRESS so this shared flag works BEFORE or AFTER the subcommand: # a plain default would be re-applied by the subparser and clobber a value the # top-level parser already set (read via getattr(args, "json", False)). @@ -666,7 +724,24 @@ def add(name, **kw): return sub.add_parser(name, parents=[common], **kw) add("login").set_defaults(fn=cmd_login) + s = add("account", description="Manage named FlowCV accounts (cookies are stored locally with owner-only permissions).") + account_sub = s.add_subparsers(dest="account_cmd", required=True) + x = account_sub.add_parser("add"); x.add_argument("name"); x.add_argument("--resume-id") + x.add_argument("--use", action="store_true", help="select this account after saving") + x.set_defaults(fn=cmd_account_add) + x = account_sub.add_parser("migrate", help="save the current legacy login/session as a named account") + x.add_argument("name"); x.add_argument("--resume-id") + x.add_argument("--use", action="store_true", help="select this account after saving") + x.set_defaults(fn=cmd_account_migrate) + x = account_sub.add_parser("list"); x.set_defaults(fn=cmd_account_list) + x = account_sub.add_parser("use"); x.add_argument("name"); x.set_defaults(fn=cmd_account_use) + x = account_sub.add_parser("remove"); x.add_argument("name"); x.set_defaults(fn=cmd_account_remove) add("resumes").set_defaults(fn=cmd_resumes) + s = add("transfer", description="Copy a resume from one named account into another account.") + s.add_argument("--from", dest="from_account", required=True, help="source account name") + s.add_argument("--to", dest="to_account", required=True, help="destination account name") + s.add_argument("--title", help="title of the new resume in the destination account") + s.set_defaults(fn=cmd_transfer) s = add("new"); s.add_argument("title"); s.set_defaults(fn=cmd_new) s = add("duplicate"); s.add_argument("title", nargs="?"); s.set_defaults(fn=cmd_duplicate) diff --git a/flowcvcli/client.py b/flowcvcli/client.py index 4ab70e5..abb18e1 100644 --- a/flowcvcli/client.py +++ b/flowcvcli/client.py @@ -234,12 +234,13 @@ def login(email, password, jar=None): return jar -def _write_session(cookie): +def _write_session(cookie, path=None): """Persist the session cookie header with owner-only perms (0o600) — it's a credential.""" - parent = os.path.dirname(SESSION_FILE) + path = path or Config.load().session_file + parent = os.path.dirname(path) if parent: os.makedirs(parent, exist_ok=True) - fd = os.open(SESSION_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w") as f: f.write(cookie) @@ -258,6 +259,10 @@ def __init__(self, config=None, resume_id=None): self._batch_depth = 0 # >0 while inside batch(): get_resume() is cached self._batch_cache = None # the one fetched resume shared across a batch + def _session_path(self): + """Keep the legacy session path patchable while isolating named accounts.""" + return self.cfg.session_file if self.cfg.account else SESSION_FILE + # ---- auth ------------------------------------------------------------- def _ensure_auth(self): """Seed the cookie jar once, in priority order: FLOWCV_COOKIE (env) -> @@ -273,8 +278,8 @@ def _ensure_auth(self): "(FLOWCV_COOKIE=flowcvsidapp=s%3A...), not just the value.") self._authed = True return - if os.path.exists(SESSION_FILE): - with open(SESSION_FILE) as f: + if os.path.exists(self._session_path()): + with open(self._session_path()) as f: cached = f.read().strip() if cached: _seed_jar(self._jar, cached) @@ -297,7 +302,7 @@ def cookie(self): def _persist(self): header = _jar_header(self._jar) - _write_session(header) + _write_session(header, self._session_path()) self._persisted = header def _maybe_persist(self): @@ -307,7 +312,7 @@ def _maybe_persist(self): return header = _jar_header(self._jar) if header and header != self._persisted: - _write_session(header) + _write_session(header, self._session_path()) self._persisted = header def relogin(self): @@ -319,7 +324,7 @@ def relogin(self): if not (self.cfg.email and self.cfg.password): return False try: - os.remove(SESSION_FILE) + os.remove(self._session_path()) except OSError: pass self._jar.clear() @@ -391,8 +396,8 @@ def _auth_rescues(self): When the seed was a stale FLOWCV_COOKIE, the cached session file written by an earlier login is often still valid, so it is tried before a login. """ - if self.cfg.cookie and os.path.exists(SESSION_FILE): - with open(SESSION_FILE) as f: + if self.cfg.cookie and os.path.exists(self._session_path()): + with open(self._session_path()) as f: cached = f.read().strip() if cached and cached != _jar_header(self._jar): self._jar.clear() diff --git a/flowcvcli/config.py b/flowcvcli/config.py index 404da82..41b6ef3 100644 --- a/flowcvcli/config.py +++ b/flowcvcli/config.py @@ -11,7 +11,9 @@ the user's environment, never from the install location, so the tool behaves the same whether it's run from source or ``pip install``-ed. """ +import json import os +import re import stat import time @@ -42,6 +44,107 @@ def backups_dir(): SESSION_FILE = os.environ.get("FLOWCV_SESSION_FILE") or os.path.join(_config_home(), "session") +def accounts_dir(): + return os.path.join(_config_home(), "accounts") + + +def current_account_file(): + return os.path.join(_config_home(), "current_account") + + +def validate_account_name(name): + if not name or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}", name): + raise ApiError("Account name must be 1-64 letters, numbers, '.', '_' or '-'.") + return name + + +def account_file(name): + return os.path.join(accounts_dir(), validate_account_name(name) + ".json") + + +def session_file_for(account=None): + explicit = os.environ.get("FLOWCV_SESSION_FILE") + if explicit: + return explicit + return os.path.join(accounts_dir(), validate_account_name(account), "session") if account else SESSION_FILE + + +def selected_account(explicit=None): + if explicit: + return validate_account_name(explicit) + env_name = os.environ.get("FLOWCV_ACCOUNT") + if env_name: + return validate_account_name(env_name) + try: + with open(current_account_file(), encoding="utf-8") as f: + name = f.read().strip() + return validate_account_name(name) if name else None + except OSError: + return None + + +def load_account(name): + path = account_file(name) + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + except FileNotFoundError: + raise ApiError(f"Unknown FlowCV account {name!r}. Run `flowcv account list`.") + except (OSError, ValueError) as e: + raise ApiError(f"Could not read FlowCV account {name!r}: {e}") + return data + + +def save_account(name, *, cookie, resume_id=None): + name = validate_account_name(name) + cookie = (cookie or "").strip() + if cookie and "=" not in cookie: + cookie = "flowcvsidapp=" + cookie + if "flowcvsidapp=" not in (cookie or ""): + raise ApiError("Cookie must include the full flowcvsidapp=name-value pair.") + os.makedirs(accounts_dir(), exist_ok=True) + path = account_file(name) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump({"cookie": cookie.strip(), "resume_id": resume_id}, f, ensure_ascii=False) + return path + + +def use_account(name): + load_account(name) + os.makedirs(_config_home(), exist_ok=True) + path = current_account_file() + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(name + "\n") + + +def list_accounts(): + try: + names = [os.path.splitext(x)[0] for x in os.listdir(accounts_dir()) if x.endswith(".json")] + except OSError: + names = [] + return sorted(names) + + +def remove_account(name): + path = account_file(name) + try: + os.remove(path) + except FileNotFoundError: + raise ApiError(f"Unknown FlowCV account {name!r}.") + session = session_file_for(name) + try: + os.remove(session) + except OSError: + pass + if selected_account() == name: + try: + os.remove(current_account_file()) + except OSError: + pass + + def _dotenv_files(): paths = [] if os.environ.get("FLOWCV_ENV_FILE"): @@ -81,20 +184,29 @@ def _pick(fv, *keys): class Config: """Resolved auth + target resume. resume_id may be None for resume-list ops.""" - def __init__(self, resume_id=None, cookie=None, email=None, password=None): + def __init__(self, resume_id=None, cookie=None, email=None, password=None, + account=None, session_file=None): self.resume_id = resume_id self.cookie = cookie self.email = email self.password = password + self.account = account + self.session_file = session_file or session_file_for(account) @classmethod - def load(cls): + def load(cls, account=None): fv = _load_dotenv() + account = selected_account(account) + profile = load_account(account) if account else {} return cls( - resume_id=_pick(fv, "FLOWCV_RESUME_ID", "RESUME_ID"), - cookie=_pick(fv, "FLOWCV_COOKIE", "COOKIE"), - email=_pick(fv, "FLOWCV_EMAIL", "EMAIL"), - password=_pick(fv, "FLOWCV_PASSWORD", "PASSWORD"), + resume_id=_pick(fv, "FLOWCV_RESUME_ID", "RESUME_ID") or profile.get("resume_id"), + cookie=(profile.get("cookie") if account else _pick(fv, "FLOWCV_COOKIE", "COOKIE")), + # Named profiles are cookie-only. Never fall back to legacy + # credentials, which may belong to a different account. + email=None if account else _pick(fv, "FLOWCV_EMAIL", "EMAIL"), + password=None if account else _pick(fv, "FLOWCV_PASSWORD", "PASSWORD"), + account=account, + session_file=session_file_for(account), ) def require_resume_id(self): @@ -122,17 +234,22 @@ def resolve_auth_source(cfg): """The auth source Client._ensure_auth would use, as a label (None if unauthed). Mirrors that method's priority: env cookie -> cached session -> credentials.""" if cfg.cookie: - return "env cookie (FLOWCV_COOKIE)" - if _session_usable(): + return (f"account cookie ({cfg.account})" if cfg.account + else "env cookie (FLOWCV_COOKIE)") + try: + session_usable = os.path.getsize(cfg.session_file) > 0 + except OSError: + session_usable = False + if session_usable: return "cached session" if cfg.email and cfg.password: return "credentials (email + password)" return None -def session_file_info(): +def session_file_info(path=None): """Perms/age of the cached session file for `doctor` (exists=False if absent).""" - path = SESSION_FILE + path = path or SESSION_FILE try: st = os.stat(path) except OSError: diff --git a/tests/test_accounts.py b/tests/test_accounts.py new file mode 100644 index 0000000..cb55f79 --- /dev/null +++ b/tests/test_accounts.py @@ -0,0 +1,64 @@ +import contextlib +import io +import json +import os +import shutil +import unittest +from unittest import mock + +from flowcvcli import cli +from flowcvcli.config import Config, save_account, use_account + + +class AccountConfigTest(unittest.TestCase): + def setUp(self): + self.root = os.path.join(os.getcwd(), ".test-account-config") + shutil.rmtree(self.root, ignore_errors=True) + + def tearDown(self): + shutil.rmtree(self.root, ignore_errors=True) + + def test_named_accounts_are_isolated_and_switchable(self): + home = os.path.join(self.root, "flowcvcli") + with mock.patch.dict(os.environ, {}, clear=True), \ + mock.patch("flowcvcli.config._config_home", return_value=home): + save_account("gmail", cookie="s%3Agmail", resume_id="G1") + save_account("qq", cookie="flowcvsidapp=s%3Aqq", resume_id="Q1") + use_account("gmail") + g = Config.load() + q = Config.load(account="qq") + self.assertEqual(g.cookie, "flowcvsidapp=s%3Agmail") + self.assertEqual(g.resume_id, "G1") + self.assertEqual(q.cookie, "flowcvsidapp=s%3Aqq") + self.assertNotEqual(g.session_file, q.session_file) + + def test_named_account_does_not_inherit_legacy_credentials(self): + home = os.path.join(self.root, "flowcvcli") + env = {"FLOWCV_EMAIL": "legacy@example.com", "FLOWCV_PASSWORD": "secret"} + with mock.patch.dict(os.environ, env, clear=True), \ + mock.patch("flowcvcli.config._config_home", return_value=home): + save_account("gmail", cookie="flowcvsidapp=s%3Agmail") + cfg = Config.load(account="gmail") + self.assertIsNone(cfg.email) + self.assertIsNone(cfg.password) + + +class TransferTest(unittest.TestCase): + def test_transfer_exports_source_and_imports_destination(self): + source = mock.Mock() + source.export_resume.return_value = {"id": "G1", "title": "Google CV"} + dest = mock.Mock() + dest.import_resume.return_value = "NEW1" + with mock.patch("flowcvcli.cli.Config.load", side_effect=[mock.Mock(), mock.Mock()]), \ + mock.patch("flowcvcli.cli.FlowCV", side_effect=[source, dest]), \ + contextlib.redirect_stdout(io.StringIO()) as out: + cli.main(["--json", "transfer", "--from", "gmail", "--to", "qq", + "--resume-id", "G1", "--title", "Copied"]) + data = json.loads(out.getvalue()) + self.assertTrue(data["success"]) + dest.import_resume.assert_called_once_with(source.export_resume.return_value, + title="Copied") + + +if __name__ == "__main__": + unittest.main()