forked from simoncadman/CUPS-Cloud-Print
/
auth.py
171 lines (142 loc) · 5.35 KB
/
auth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# CUPS Cloudprint - Print via Google Cloud Print
# Copyright (C) 2011 Simon Cadman
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json, os, grp, sys, grp
from oauth2client import client
from oauth2client import multistore_file
from cloudprintrequestor import cloudprintrequestor
class Auth:
clientid = "843805314553.apps.googleusercontent.com"
clientsecret = 'MzTBsY4xlrD_lxkmwFbBrvBv'
config = '/etc/cloudprint.conf'
def GetLPID():
"""Delete an account from the configuration file
Args:
storage: storage, instance of storage to store credentials in.
userid: string, reference for the account
Returns:
deleted: int , None on failure
"""
# try lp first, then cups#
lpgrp = None
try:
lpgrp = grp.getgrnam('lp')
except:
try:
lpgrp = grp.getgrnam('cups')
except:
pass
if lpgrp == None:
return None
else:
return lpgrp.gr_gid
GetLPID = staticmethod(GetLPID)
def DeleteAccount(userid=None): # pragma: no cover
"""Delete an account from the configuration file
Args:
storage: storage, instance of storage to store credentials in.
userid: string, reference for the account
Returns:
deleted: boolean , true on success
"""
storage = multistore_file.get_credential_storage(
Auth.config,
Auth.clientid,
userid,
['https://www.googleapis.com/auth/cloudprint'])
return storage.delete()
DeleteAccount = staticmethod(DeleteAccount)
def AddAccount(storage, userid=None): # pragma: no cover
"""Adds an account to the configuration file
Args:
storage: storage, instance of storage to store credentials in.
userid: string, reference for the account
Returns:
credentials: A credentials instance with the account details
"""
if userid == None:
userid = raw_input("Name for this user account ( eg something@gmail.com )? ")
while True:
flow = client.OAuth2WebServerFlow(client_id=Auth.clientid,
client_secret=Auth.clientsecret,
scope='https://www.googleapis.com/auth/cloudprint',
user_agent=userid)
auth_uri = flow.step1_get_authorize_url()
print("Open this URL, grant access to CUPS Cloud Print, then provide the code displayed : \n\n" + auth_uri + "\n")
code = raw_input('Code from Google: ')
try:
print("")
credentials = flow.step2_exchange(code)
storage.put(credentials)
# fix permissions
try:
os.chmod(Auth.config, 0640)
os.chown(Auth.config, 0, Auth.GetLPID())
except:
sys.stderr.write("DEBUG: Cannot alter file permissions\n")
return credentials
except Exception as e:
print("\nThe code does not seem to be valid ( " + str(e) + " ), please try again.\n")
AddAccount = staticmethod(AddAccount)
def SetupAuth(interactive=False):
"""Sets up requestors with authentication tokens
Args:
interactive: boolean, when set to true can prompt user, otherwise returns False if authentication fails
Returns:
requestor, storage: Authenticated requestors and an instance of storage
"""
modifiedconfig = False
# parse config file and extract useragents, which we use for account names
userids = []
if os.path.exists( Auth.config ):
content_file = open(Auth.config, 'r')
content = content_file.read()
data = json.loads(content)
for user in data['data']:
userids.append(str(user['credential']['user_agent']))
if len(userids) == 0:
userids = [ None ]
requestors = []
for userid in userids:
storage = multistore_file.get_credential_storage(
Auth.config,
Auth.clientid,
userid,
['https://www.googleapis.com/auth/cloudprint'])
credentials = storage.get()
if not credentials and interactive: # pragma: no cover
credentials = Auth.AddAccount(storage, userid)
modifiedconfig = True
if userid == None:
userid = credentials.user_agent
elif not interactive and not credentials:
return False
# renew if expired
requestor = cloudprintrequestor()
if credentials.access_token_expired: # pragma: no cover
credentials.refresh(requestor)
requestor = credentials.authorize(requestor)
requestor.setAccount(userid)
requestors.append(requestor)
# fix permissions
if modifiedconfig: # pragma: no cover
try:
os.chmod(Auth.config, 0640)
os.chown(Auth.config, 0, Auth.GetLPID())
except:
sys.stderr.write("DEBUG: Cannot alter file permissions\n")
pass
return requestors, storage
SetupAuth = staticmethod(SetupAuth)