blob: 87ec1ccf00c861e34e87408b9b913bcc2d8df32f [file] [log] [blame]
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +00001#!/usr/bin/env python
2# Copyright 2015 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Manages cached OAuth2 tokens used by other depot_tools scripts.
7
8Usage:
9 depot-tools-auth login codereview.chromium.org
10 depot-tools-auth info codereview.chromium.org
11 depot-tools-auth logout codereview.chromium.org
12"""
13
14import logging
15import optparse
16import sys
iannucci@chromium.org0703ea22016-04-01 01:02:42 +000017import os
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +000018
19from third_party import colorama
20
21import auth
22import subcommand
23
24__version__ = '1.0'
25
26
27@subcommand.usage('<hostname>')
28def CMDlogin(parser, args):
29 """Performs interactive login and caches authentication token."""
30 # Forcefully relogin, revoking previous token.
31 hostname, authenticator = parser.parse_args(args)
32 authenticator.logout()
33 authenticator.login()
34 print_token_info(hostname, authenticator)
35 return 0
36
37
38@subcommand.usage('<hostname>')
39def CMDlogout(parser, args):
40 """Revokes cached authentication token and removes it from disk."""
41 _, authenticator = parser.parse_args(args)
42 done = authenticator.logout()
43 print 'Done.' if done else 'Already logged out.'
44 return 0
45
46
47@subcommand.usage('<hostname>')
48def CMDinfo(parser, args):
49 """Shows email associated with a cached authentication token."""
50 # If no token is cached, AuthenticationError will be caught in 'main'.
51 hostname, authenticator = parser.parse_args(args)
52 print_token_info(hostname, authenticator)
53 return 0
54
55
56def print_token_info(hostname, authenticator):
57 token_info = authenticator.get_token_info()
58 print 'Logged in to %s as %s.' % (hostname, token_info['email'])
59 print ''
60 print 'To login with a different email run:'
61 print ' depot-tools-auth login %s' % hostname
62 print 'To logout and purge the authentication token run:'
63 print ' depot-tools-auth logout %s' % hostname
64
65
66class OptionParser(optparse.OptionParser):
67 def __init__(self, *args, **kwargs):
68 optparse.OptionParser.__init__(
69 self, *args, prog='depot-tools-auth', version=__version__, **kwargs)
70 self.add_option(
71 '-v', '--verbose', action='count', default=0,
72 help='Use 2 times for more debugging info')
73 auth.add_auth_options(self, auth.make_auth_config(use_oauth2=True))
74
75 def parse_args(self, args=None, values=None):
76 """Parses options and returns (hostname, auth.Authenticator object)."""
77 options, args = optparse.OptionParser.parse_args(self, args, values)
78 levels = [logging.WARNING, logging.INFO, logging.DEBUG]
79 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
80 auth_config = auth.extract_auth_config_from_options(options)
81 if len(args) != 1:
82 self.error('Expecting single argument (hostname).')
83 if not auth_config.use_oauth2:
84 self.error('This command is only usable with OAuth2 authentication')
85 return args[0], auth.get_authenticator_for_host(args[0], auth_config)
86
87
88def main(argv):
89 dispatcher = subcommand.CommandDispatcher(__name__)
90 try:
91 return dispatcher.execute(OptionParser(), argv)
92 except auth.AuthenticationError as e:
93 print >> sys.stderr, e
94 return 1
95
96
97if __name__ == '__main__':
iannucci@chromium.org0703ea22016-04-01 01:02:42 +000098 colorama.init(wrap="TERM" not in os.environ)
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +000099 try:
100 sys.exit(main(sys.argv[1:]))
101 except KeyboardInterrupt:
102 sys.stderr.write('interrupted\n')
103 sys.exit(1)