blob: bd2241649bf9bc5c1cefbb301d8af014070487c1 [file] [log] [blame]
Joe Gregorio695fdc12011-01-16 16:46:55 -05001# Copyright (C) 2010 Google Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Command-line tools for authenticating via OAuth 2.0
16
Joe Gregorio7c22ab22011-02-16 15:32:39 -050017Do the OAuth 2.0 Web Server dance for a command line application. Stores the
18generated credentials in a common file that is used by other example apps in
19the same directory.
Joe Gregorio695fdc12011-01-16 16:46:55 -050020"""
21
22__author__ = 'jcgregorio@google.com (Joe Gregorio)'
Joe Gregorio7c22ab22011-02-16 15:32:39 -050023__all__ = ['run']
Joe Gregorio695fdc12011-01-16 16:46:55 -050024
Joe Gregorio695fdc12011-01-16 16:46:55 -050025
Joe Gregoriodeeb0202011-02-15 14:49:57 -050026def run(flow, storage):
Joe Gregorio695fdc12011-01-16 16:46:55 -050027 """Core code for a command-line application.
Joe Gregoriofffa7d72011-02-18 17:20:39 -050028
29 Args:
30 flow: Flow, an OAuth 2.0 Flow to step through.
31 storage: Storage, a Storage to store the credential in.
32
33 Returns:
34 Credentials, the obtained credential.
35
36 Exceptions:
37 RequestError: if step2 of the flow fails.
Joe Gregorio695fdc12011-01-16 16:46:55 -050038 """
Joe Gregoriodeeb0202011-02-15 14:49:57 -050039 authorize_url = flow.step1_get_authorize_url('oob')
Joe Gregorio695fdc12011-01-16 16:46:55 -050040
41 print 'Go to the following link in your browser:'
42 print authorize_url
43 print
44
Joe Gregorio49e94d82011-01-28 16:36:13 -050045 accepted = 'n'
46 while accepted.lower() == 'n':
47 accepted = raw_input('Have you authorized me? (y/n) ')
48 code = raw_input('What is the verification code? ').strip()
Joe Gregorio695fdc12011-01-16 16:46:55 -050049
Joe Gregoriofffa7d72011-02-18 17:20:39 -050050 try:
51 credentials = flow.step2_exchange(code)
52 except RequestError:
53 sys.exit('The authentication has failed.')
Joe Gregorio695fdc12011-01-16 16:46:55 -050054
Joe Gregoriodeeb0202011-02-15 14:49:57 -050055 storage.put(credentials)
56 credentials.set_store(storage.put)
57
58 print 'You have successfully authenticated.'
59
60 return credentials