This repository was archived by the owner on Sep 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
797 lines (719 loc) · 27.8 KB
/
cli.py
File metadata and controls
797 lines (719 loc) · 27.8 KB
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
# pylint: disable=no-self-use
# pylint: disable=too-many-statements
# pylint: disable=raise-missing-from
"""CLI tool for ARgorithm made using typer.
Example:
$ ARgorithm --help
"""
import os
import sys
import re
import json
import traceback
import requests
import typer
from halo import Halo
import ARgorithmToolkit
from ARgorithmToolkit.security import injection_check,execution_check
from ARgorithmToolkit.parser import input_data,create,validateconfig,ValidationError
CLOUD_URL = "https://argorithm.el.r.appspot.com"
CACHE_DIR = typer.get_app_dir("ARgorithm")
app = typer.Typer(help="ARgorithm CLI")
class Messager():
"""Class for pretty printing messages using typer."""
def msg(self,tag:str,title:str,message:str,color:str):
"""Pretty messaging for standard log messages."""
code = typer.style(f"[{tag.upper()}]: {title.upper()}" , fg=color , bold=True)
typer.echo(code)
if message:
typer.echo(message)
def info(self,title:str,message:str=""):
"""Information message."""
self.msg("info",title,message,typer.colors.BLUE)
def warn(self,title:str,message:str=""):
"""Warning message."""
self.msg("error",title,message,typer.colors.YELLOW)
def fail(self,title:str,message:str=""):
"""Error message."""
self.msg("critical error",title,message,typer.colors.RED)
def good(self,title:str,message:str=""):
"""Success message."""
self.msg("success",title,message,typer.colors.GREEN)
def menuitem(self,argorithm):
"""pretty print argorithm details."""
head = typer.style(f"- {argorithm['argorithmID']}",fg=typer.colors.GREEN,bold=True)
typer.echo(head)
typer.secho(f"by {argorithm['maintainer']}",fg=typer.colors.CYAN)
if argorithm['description']:
typer.echo(f"{argorithm['description']}")
if argorithm['parameters']:
typer.echo("Parameters")
for key in argorithm['parameters']:
if argorithm['parameters'][key]['description']:
typer.echo(f"- {key} : {argorithm['parameters'][key]['description']}")
else:
typer.echo(f"- {key}")
typer.echo()
def state(self,states):
"""pretty print states."""
states = states['data']
for state in states:
typer.echo('\n'+'-'*50)
typer.secho(state['state_type'],bold=True)
typer.secho('\t'+state['comments'],fg=typer.colors.CYAN)
if state['state_def']:
for key in state['state_def']:
typer.echo(f"\t{key} : {state['state_def'][key]}")
msg = Messager()
class Settings():
"""handles connection endpoints."""
endpoint:str=CLOUD_URL
def get_endpoint(self):
"""returns required endpoint."""
config_file = os.path.join(CACHE_DIR , "config")
if os.path.isfile(config_file):
with open(config_file,"r") as conf:
self.endpoint = conf.read()
return self.endpoint
def set_endpoint(self,url):
"""set up cloud endpoint."""
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.get(url+"/argorithm")
if rq.status_code == 200:
msg.good("Connected",f"web requests will now go to {url}")
else:
raise AttributeError("Not a server endpoint")
except ValueError as ve:
msg.warn("Please try again with proper URL")
raise typer.Exit(1) from ve
except AttributeError as ex:
msg.fail(str(ex))
raise typer.Exit(1) from ex
except Exception as ex:
msg.fail("Endpoint couldnt be found.")
print(ex)
raise typer.Exit(2) from ex
config_file = os.path.join(CACHE_DIR , "config")
with open(config_file,'w') as config:
config.write(url)
app_settings = Settings()
class AuthManager():
"""Handles authentication."""
def __init__(self):
"""sets up credfile to store credentials."""
self.credfile = os.path.join(CACHE_DIR,".credentials")
def register(self):
"""registers account."""
email = typer.prompt("Enter email address")
msg.info("Password criteria",'- between 8 to 25 characters\n - contains atleast one number\n - contains atleast lower case alphabet\n - contains atleast uppercase alphabet')
rules = r"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,25}$"
password = typer.prompt("Enter password",confirmation_prompt=True,hide_input=True)
if not re.search(rules,password):
msg.warn("password unacceptable")
typer.Exit(1)
return
url = app_settings.get_endpoint()+'/programmers/register'
data = {
"username" : email,
"password" : password
}
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,data)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
msg.good("Account created","These credentials will be used as both programmer and user credentials")
return
if rq.status_code == 409:
msg.warn("Invalid email","email is already in use. Try login")
raise typer.Exit(0)
msg.fail("Error","Contact developer")
def login_prompt(self):
"""login prompt to enter credentials."""
email = typer.prompt("Enter email address")
password = typer.prompt("Enter password",hide_input=True)
url = f"{app_settings.get_endpoint()}/programmers/login"
data = {
"username" : email,
"password" : password
}
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,data)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 404:
msg.warn("User not found","please enter valid email")
elif rq.status_code == 500:
msg.fail("Server error","contact developer")
elif rq.status_code == 401:
msg.warn("incorrect password")
elif rq.status_code == 402:
msg.warn("please verify account first")
elif rq.status_code == 200:
msg.good("logged in successfully","credentials saved in cache")
token = json.loads(rq.content)['access_token']
with open(self.credfile,'w+') as cred:
cred.write(token)
return token
raise typer.Exit(1)
def get_token(self,flag=False):
"""returns valid authorization token."""
url = app_settings.get_endpoint()
if os.path.isfile(self.credfile):
with open(self.credfile,'r') as cred:
token = cred.read()
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(f"{url}/programmers/verify" , headers = {"authorization" : "Bearer "+token})
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
override = False
if flag:
override = typer.confirm("Found existing valid token. do you want to login again?")
if not override:
return token
else:
msg.warn("Valid credentials not found","Please enter login credentials again")
token = self.login_prompt()
with open(self.credfile,'w+') as cred:
cred.write(token)
return token
def get_header(self):
"""Get authentication header."""
header=None
if self.auth_check():
token = self.get_token()
header={"authorization":"Bearer "+token}
return header
def auth_check(self):
"""checks if AUTH is enabled on server."""
try:
url = app_settings.get_endpoint() + "/auth"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.get(url)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
return True
return False
except Exception as ex:
msg.warn("authentication error",str(ex))
raise typer.Abort()
def remove_token(self):
"""logout by deleting access token."""
try:
os.remove(self.credfile)
msg.good("Logged out")
except Exception:
msg.warn("No credentials found")
authmanager = AuthManager()
def name_check(value:str):
"""checks validity of argorithmID."""
rules = r"^[A-Za-z_]+$"
m = re.search(rules,value)
if m is None:
msg.fail("Invalid name" , "argorithm name should be [A-Za-z_]")
raise typer.Exit(code=1)
return value
def autocomplete(incomplete:str):
"""autocomplete function for finding argorithms."""
local_directory , incomplete = os.path.split(incomplete)
if local_directory == '':
local_directory = '.'
files = os.listdir(local_directory)
res = []
l = len(incomplete)
for filename in files:
if filename[:l] == incomplete and filename[-3:] == '.py':
if local_directory == '.':
res.append(filename)
else:
res.append(os.path.join(local_directory,filename))
return res
class CodeManager():
"""Handles file verification, testing and submissions."""
def __init__(self,filename):
"""gets filepath for code file and config file."""
directory , argorithm_file = os.path.split(filename)
argorithmID = name_check(argorithm_file[:-3])
directory = os.getcwd() if not directory else directory
self.codepath = os.path.join(directory,argorithm_file)
self.configpath = os.path.join(directory,argorithmID+".config.json")
if not os.path.isfile(self.codepath):
msg.warn("Python file not found",'use the init command first')
raise typer.Abort()
if not os.path.isfile(self.configpath):
msg.warn("config file not found",'use the configure command first')
raise typer.Abort()
def verify(self):
"""checks whether files are valid or not."""
injection_check(self.codepath)
validateconfig(self.configpath)
def test(self,prompt:bool=False):
"""Execute code locally."""
try:
with open(self.configpath,'r') as configfile:
config = json.load(configfile)
parameters = config['example']
if prompt:
user = typer.confirm("Do you want to add user input?")
if user:
parameters = input_data(config['parameters'])
if parameters and prompt:
typer.echo("using parameters:")
for key in parameters:
typer.echo(f"- {key} : {parameters[key]}")
return execution_check(self.codepath,self.configpath,parameters)
except AssertionError:
msg.warn("Execution Failed","execution should return ARgorithmToolkit.StateSet")
raise typer.Exit(1)
except Exception:
msg.warn("Execution Failed")
traceback.print_exception(*sys.exc_info())
raise typer.Exit(1)
def generate_submission(self):
"""Generate the files for submission."""
_ , local_file = os.path.split(self.codepath)
with open(self.configpath,'r') as configfile:
data = json.load(configfile)
files = [
('file', (local_file, open(self.codepath, 'rb'), 'application/octet')),
('data', ('data', json.dumps(data), 'application/json')),
]
header = authmanager.get_header()
return files,header
def submit(self):
"""Submit code to server."""
files,header = self.generate_submission()
url = app_settings.get_endpoint()+"/argorithms/insert"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,files=files,headers=header)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
msg.good("Submitted")
elif rq.status_code == 409:
msg.warn("Already exists","An argorithm with this name already exists,try another argorithm name")
elif rq.status_code == 406:
msg.warn("File name was invalid","The name shoud be of type [A-Za-z_]")
elif rq.status_code == 400:
msg.warn("Incorrect file format","please refer documentation")
else:
msg.fail("Application error")
def update(self):
"""Update code in servers."""
files,header = self.generate_submission()
url = app_settings.get_endpoint()+"/argorithms/update"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,files=files,headers=header)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
msg.good("updated")
elif rq.status_code == 404:
msg.warn("Not found","Try submit command to add argorithm to server")
elif rq.status_code == 401:
msg.warn("Unauthorized","Only author of argorithm or admin is allowed to alter argorithms")
else:
msg.fail("Application error")
@app.command()
def connect(
local:bool = typer.Option(False,"--local",'-l',help="Connects to server running on localhost",show_default=False)
):
"""Connect to your endpoint.
More info at https://argorithm.github.io/toolkit/cli#connect
"""
if local:
endpoint = "http://localhost"
else:
endpoint = typer.prompt("Enter server endpoint",default=app_settings.get_endpoint())
app_settings.set_endpoint(endpoint)
@app.command()
def init(
name:str = typer.Argument(...,help="The name given to the argorithm [A-Za-z_]",callback=name_check)
):
"""Create Blank code template and config template for ARgorithm.
More info at https://argorithm.github.io/toolkit/cli#init
"""
typer.echo(f"Creating empty template for {name}")
with open(os.path.join(ARgorithmToolkit.__path__[0],'data/template.py',),'rb') as template:
starter = template.read()
filename = f"{name}.py"
with open(filename , "wb") as codefile:
codefile.write(starter)
msg.good("Template generated","refer documentation at https://argorithm.github.io/toolkit")
@app.command()
def configure(
filepath:str=typer.Argument(... , help="The code file to be configured" , autocompletion=autocomplete),
blank:bool=typer.Option(False,'-b','--blank',help="create blank config file"),
validate:bool=typer.Option(False,'-v','--validate',help="only validate existing config file,Dont create")
):
"""Create configuration file for argorithm.
More info at https://argorithm.github.io/toolkit/cli#configure
"""
directory,filename = os.path.split(filepath)
name = filename[:-3]
if not os.path.isfile(filepath):
msg.warn("Python file not found",'use the init command first')
raise typer.Abort()
configpath = os.path.join(os.getcwd(),directory,name+".config.json")
try:
validateconfig(configpath)
typer.echo("Valid config file found")
if not blank:
if not validate:
redo = typer.confirm(f"Do you remake the {name}.config.json?")
if redo:
create(configpath)
raise typer.Exit(0)
except ValidationError:
if not validate and not blank:
create(configpath)
raise typer.Exit(0)
except FileNotFoundError:
if validate:
msg.warn("Config file not found")
raise typer.Exit(0)
if not blank:
create(configpath)
raise typer.Exit(0)
config = {
"argorithmID" : name,
"file" : name+".py",
"function" : "run",
"parameters" : {},
"example" : {},
"description" : ""
}
with open(configpath, "w") as configfile:
json.dump(config,configfile,indent=4)
@app.command()
def submit(
filename:str=typer.Argument(... , help="The code file to be submitted" , autocompletion=autocomplete)
):
"""Submit argorithms to server.
More info at https://argorithm.github.io/toolkit/cli#submit
"""
code = CodeManager(filename)
with Halo(text='Verifying', spinner='dots'):
code.verify()
msg.good("Files verified")
with Halo(text='Testing', spinner='dots'):
code.test(prompt=False)
msg.good("Files verified")
code.submit()
@app.command()
def update(
filename:str=typer.Argument(... , help="The code file to be submitted" , autocompletion=autocomplete)
):
"""Updates pre existing argorithms at server.
More info at https://argorithm.github.io/toolkit/cli#update
"""
code = CodeManager(filename)
with Halo(text='Verifying', spinner='dots'):
code.verify()
msg.good("Files verified")
with Halo(text='Testing', spinner='dots'):
code.test(prompt=False)
msg.good("Files verified")
code.update()
@app.command()
def delete(
argorithm_id:str = typer.Argument(... , help="argorithmID of function to be deleted.")
):
"""Deletes argorithm from server.
More info at https://argorithm.github.io/toolkit/cli#delete
"""
params = search(argorithm_id)
flag = typer.confirm("Are you sure you want to delete it?")
if not flag:
typer.echo("Not deleting")
raise typer.Abort()
header=authmanager.get_header()
data = {
"argorithmID" : params["argorithmID"],
}
url = app_settings.get_endpoint()+"/argorithms/delete"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,json=data,headers=header)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
msg.info("Deleted successfully",)
elif rq.status_code == 401:
msg.warn("Not authorized","only author of argorithm or admin can delete it")
else:
msg.fail("application error")
def search(argid,show=True):
"""Searches argorithm on server."""
url = app_settings.get_endpoint()+"/argorithms/view/"+argid
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.get(url)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
data = json.loads(rq.content)
if show:
typer.echo("Found argorithm")
msg.menuitem(data)
return data
if rq.status_code == 404:
msg.warn("Not found",f"{argid} not found in database")
raise typer.Exit(1)
msg.fail("Application error")
raise typer.Exit(1)
@app.command("list")
def list_argorithms():
"""Get list of argorithms in server.
More info at https://argorithm.github.io/toolkit/cli#list
"""
url = app_settings.get_endpoint()+"/argorithms/list"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.get(url)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
menu = json.loads(rq.content)
if len(menu) == 0:
msg.warn("No argorithms")
raise typer.Exit(1)
for item in menu:
msg.menuitem(item)
@app.command()
def test(
argorithm_id:str = typer.Argument(... , help="argorithmID of function to be called. If not passed then menu will be presented"),
output:bool = typer.Option(False,'--output','-o',help="print results in json format",show_default=False),
user_input:bool = typer.Option(False,'--user-input','-u',help="if present, takes input from user",show_default=False),
):
"""Test argorithms stored in server.
More info at https://argorithm.github.io/toolkit/cli#test
"""
params = search(argorithm_id,show=not output)
header=authmanager.get_header()
data = {
"argorithmID" : params["argorithmID"],
"parameters" : params["example"]
}
if user_input:
data["parameters"] = input_data(params["parameters"])
url = app_settings.get_endpoint()+"/argorithms/run"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,json=data,headers=header)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
if output:
print(rq.text)
else:
msg.state(json.loads(rq.content))
elif rq.status_code == 401:
msg.warn("Authentication failed",json.loads(rq.content)['detail'])
else:
msg.fail("application error")
@app.command()
def execute(
filename:str=typer.Argument(... , help="The code file to be submitted" , autocompletion=autocomplete)
):
"""Execute locally stored ARgorithms.
More info at https://argorithm.github.io/toolkit/cli#execute
"""
code = CodeManager(filename)
code.verify()
states = [x.content for x in code.test(prompt=True)]
msg.state({"data" : states})
account_app = typer.Typer(help="Manages account")
app.add_typer(account_app,name="account")
@account_app.command()
def login():
"""Log in to ARgorithmServer.
Only is AUTH is enabled on server. More info at
https://argorithm.github.io/toolkit/cli#login
"""
if not authmanager.auth_check():
msg.warn("AUTH disabled at server")
raise typer.Exit(0)
authmanager.get_token(flag=True)
@account_app.command()
def signup():
"""Create new programmer and user account in ARgorithmServer.
Only is AUTH is enabled on server. More info at
https://argorithm.github.io/toolkit/cli#signup
"""
if not authmanager.auth_check():
msg.warn("AUTH disabled at server")
raise typer.Exit(0)
authmanager.register()
@account_app.command()
def logout():
"""Remove pre-existing login credentials.
More info at https://argorithm.github.io/toolkit/cli#logout
"""
authmanager.remove_token()
admin_app = typer.Typer(help="Administrator level methods")
app.add_typer(admin_app,name="admin")
@admin_app.callback()
def admin_auth_check():
"""Check if auth is enabled for admin routes."""
if not authmanager.auth_check():
msg.warn("AUTH is disabled at this endpoint")
raise typer.Exit(1)
@admin_app.command()
def grant(
email:str=typer.Argument( ... , help="The account email that would be granted admin access")
):
"""Grants admin acess.
More info at https://argorithm.github.io/toolkit/cli#grant
"""
data = {
"email" : email
}
header=authmanager.get_header()
url = app_settings.get_endpoint()+"/admin/grant"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,json=data,headers=header)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
msg.good("granted admin priveleges")
elif rq.status_code == 401:
msg.warn("Not authorized","You need admin priveleges")
elif rq.status_code == 406:
msg.warn("Blacklisted email","This email is blacklisted thus cannot be granted admin priveleges")
elif rq.status_code == 404:
msg.warn("Not found","No such email registered")
else:
msg.fail("Application Error")
@admin_app.command()
def revoke(
email:str=typer.Argument( ... , help="The account email that would be lose admin access")
):
"""Revokes admin acess.
More info at https://argorithm.github.io/toolkit/cli#revoke
"""
data = {
"email" : email
}
header=authmanager.get_header()
url = app_settings.get_endpoint()+"/admin/revoke"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,json=data,headers=header)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
msg.good("revoked admin priveleges")
elif rq.status_code == 401:
msg.warn("Not authorized","You need admin priveleges")
elif rq.status_code == 404:
msg.warn("Not found","No such email registered")
else:
msg.fail("Application Error")
@admin_app.command("delete")
def account_delete(
email:str=typer.Argument( ... , help="The account email that would be granted admin access"),
user:bool=typer.Option(False,'-u','--user',help="If flag is present, it will delete the user account")
):
"""Deletes account.
Requires admin priveleges. More info at
https://argorithm.github.io/toolkit/cli#delete_1
"""
data = {
"email" : email
}
header=authmanager.get_header()
if user:
url = app_settings.get_endpoint()+"/admin/delete_user"
else:
url = app_settings.get_endpoint()+"/admin/delete_programmer"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,json=data,headers=header)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
msg.good("deleted account")
elif rq.status_code == 401:
msg.warn("Not authorized","You need admin priveleges")
elif rq.status_code == 404:
msg.warn("Not found","No such email registered")
else:
msg.fail("Application Error")
@admin_app.command()
def blacklist(
email:str=typer.Argument( ... , help="The account email that would be granted admin access")
):
"""Blacklists account.
Requires admin priveleges. More info at
https://argorithm.github.io/toolkit/cli#blacklist
"""
data = {
"email" : email
}
header=authmanager.get_header()
url = app_settings.get_endpoint()+"/admin/black_list"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,json=data,headers=header)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
msg.good("blacklisted account")
elif rq.status_code == 401:
msg.warn("Not authorized","You need admin priveleges")
elif rq.status_code == 404:
msg.warn("Not found","No such email registered")
else:
msg.fail("Application Error")
@admin_app.command()
def whitelist(
email:str=typer.Argument( ... , help="The account email that would be granted admin access")
):
"""Whitelist accounts.
Requires admin priveleges. More info at
https://argorithm.github.io/toolkit/cli#whitelist
"""
data = {
"email" : email
}
header=authmanager.get_header()
url = app_settings.get_endpoint()+"/admin/white_list"
try:
with Halo(text='Connecting', spinner='dots'):
rq = requests.post(url,json=data,headers=header)
except requests.RequestException as rqe:
msg.fail("Connection failed",str(rqe))
raise typer.Abort()
if rq.status_code == 200:
msg.good("whitelisted account")
elif rq.status_code == 401:
msg.warn("Not authorized","You need admin priveleges")
elif rq.status_code == 404:
msg.warn("Not found","No such email registered")
else:
msg.fail("Application Error")