Skip to content

Commit 26447d1

Browse files
authored
Add exception for two-factor required (#1357)
* Add exception for two-factor required * Update tools/plex-gettoken.py with 2FA exception
1 parent 41f6b9c commit 26447d1

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

plexapi/exceptions.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,8 @@ class Unsupported(PlexApiException):
2929
class Unauthorized(BadRequest):
3030
""" Invalid username/password or token. """
3131
pass
32+
33+
34+
class TwoFactorRequired(Unauthorized):
35+
""" Two factor authentication required. """
36+
pass

plexapi/myplex.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
log, logfilter, utils)
1313
from plexapi.base import PlexObject
1414
from plexapi.client import PlexClient
15-
from plexapi.exceptions import BadRequest, NotFound, Unauthorized
15+
from plexapi.exceptions import BadRequest, NotFound, Unauthorized, TwoFactorRequired
1616
from plexapi.library import LibrarySection
1717
from plexapi.server import PlexServer
1818
from plexapi.sonos import PlexSonosClient
@@ -237,6 +237,8 @@ def query(self, url, method=None, headers=None, timeout=None, **kwargs):
237237
errtext = response.text.replace('\n', ' ')
238238
message = f'({response.status_code}) {codename}; {response.url} {errtext}'
239239
if response.status_code == 401:
240+
if "verification code" in response.text:
241+
raise TwoFactorRequired(message)
240242
raise Unauthorized(message)
241243
elif response.status_code == 404:
242244
raise NotFound(message)

tools/plex-gettoken.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,16 @@
44
Plex-GetToken is a simple method to retrieve a Plex account token.
55
"""
66
from getpass import getpass
7+
from plexapi.exceptions import TwoFactorRequired
78
from plexapi.myplex import MyPlexAccount
89

910
username = input("Plex username: ")
1011
password = getpass("Plex password: ")
11-
code = input("Plex 2FA code (leave blank for none): ")
1212

13-
account = MyPlexAccount(username, password, code=code)
13+
try:
14+
account = MyPlexAccount(username, password)
15+
except TwoFactorRequired:
16+
code = input("Plex 2FA code: ")
17+
account = MyPlexAccount(username, password, code=code)
18+
1419
print(account.authenticationToken)

0 commit comments

Comments
 (0)