ungleich-otp/otpauth/management/commands/ungleichotpclient.py

92 lines
2.9 KiB
Python

from django.conf import settings
from django.core.management.base import BaseCommand
import pyotp
import json
import urllib.request
import urllib.error
import sys
class Command(BaseCommand):
help = 'Access ungleichotp'
def add_arguments(self, parser):
parser.add_argument('--server-url', required=True)
# For creating / verifying
parser.add_argument('--name')
parser.add_argument('--realm')
parser.add_argument('--token')
# How to authenticate against ungleich-otp
parser.add_argument('--auth-name', required=True)
parser.add_argument('--auth-realm', required=True)
parser.add_argument('--auth-token')
parser.add_argument('--auth-seed')
parser.add_argument('command', choices=['create',
'delete',
'list',
'verify'], help='Action to take')
def handle(self, *args, **options):
command_to_verb = { 'create': 'POST',
'delete': 'DELETE',
'list': 'GET' }
if not options['auth_token']:
if not options['auth_seed']:
print("Either token or seed are required")
sys.exit(1)
else:
options['auth_token'] = pyotp.TOTP(options['auth_seed']).now()
to_send = {}
# Our credentials
to_send['auth_token'] = options['auth_token']
to_send['auth_name'] = options['auth_name']
to_send['auth_realm'] = options['auth_realm']
if options['command'] in ["create", "verify"]:
if not options['name'] or not options['realm']:
print("Need to specify --name and --realm")
sys.exit(1)
if options['command'] == "verify" and not options['token']:
print("Need to specify --token for verify")
sys.exit(1)
# Client credentials to be verified
to_send['name'] = options['name']
to_send['realm'] = options['realm']
to_send['token'] = options['token']
if options['command'] == "verify":
options['server_url'] = "{}/verify".format(options['server_url'])
print("{} {} {}".format(args, options, to_send))
self.rest_send(options['server_url'], to_send)
# Logically: how can we create if we already send realm/name/token ?
# Need to use auth* (?)
@staticmethod
def rest_send(serverurl, to_send):
data = json.dumps(to_send).encode("utf-8")
req = urllib.request.Request(url=serverurl,
data=data,
headers={'Content-Type': 'application/json'},
method='POST')
f = urllib.request.urlopen(req)
if f.status == 200:
return True
return False