-
Notifications
You must be signed in to change notification settings - Fork 4
/
genToken.sh
executable file
·82 lines (73 loc) · 1.9 KB
/
genToken.sh
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
#!/bin/bash
#----------------------------------------------------------------------------------------------------
# Script to generate access token for Gmail blocklet.
# Requires jq - https://stedolan.github.io/jq
#----------------------------------------------------------------------------------------------------
# Default config path.
configFile="~/.gmail"
# Read CLI arguments.
while getopts ":c:" opt; do
case $opt in
c) configFile="$OPTARG";;
\?) echo "Invalid option -$OPTARG" >&2;;
esac
done
eval configFile=$configFile;
source $configFile || exit 1
eval tokenFile=$tokenFile
scope="https://www.googleapis.com/auth/gmail.labels"
redirectURL="http://localhost:"
# Find a random unused local port.
while :
do
if [[ "$(netstat -lntu | grep -c ":$port")" -gt "0" ]]
then
port=$(( $RANDOM % 4000 ))
else
redirectURL+="$port"
break
fi
done
# Generates JSON which has to be POSTed.
generateJSON() {
cat << EOF
{
"code":"$oauthCode",
"client_id":"$clientID",
"client_secret":"$clientSecret",
"grant_type":"authorization_code",
"redirect_uri":"$redirectURL",
}
EOF
}
# Open user consent window.
echo "Opening user-consent in web browser..."
sleep 2
authURL="\
https://accounts.google.com/o/oauth2/v2/auth?\
client_id=$clientID&\
redirect_uri=$redirectURL&\
response_type=code&\
scope=$scope&\
access_type=offline"
xdg-open $authURL
if [[ $? != 0 ]]
then
echo -e "Could not open web browser. Open this link manually:\n$authURL"
sleep 10
fi
# Fetch the authorization code.
oauthCode=`nc -lW 1 $port | head -1 | sed -nr "s/.*code=(.*)&.*/\1/p"`
if [[ $? != 0 ]]
then
echo "Authorization code fetched successfully."
else
echo "Failed to get authorization code."
exit 33
fi
# Fetch and save access, refresh tokens as JSON.
mkdir -p $(dirname $tokenFile);
touch $tokenFile;
curl -s https://www.googleapis.com/oauth2/v4/token \
-H "Content-Type: application/json" \
-d "$(generateJSON)" > $tokenFile;