Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

# -*- coding: utf-8 -*- 

""" 

authserver 

========== 

Authentication server for ther macsServer. 

 

The main purpose of the authentication server is to issue empty HTTP responses 

with status codes set according to the access restictions for the requesting 

user. Furthermore, it serves the login page and performs access logs after 

processing the request. 

""" 

 

import os 

import tornado.web 

import tornado.ioloop 

from tornado import gen 

 

import re 

import json 

import base64 

import uuid 

import urlparse 

 

import datetime 

import dateutil.tz as datetz 

 

import bcrypt 

 

import motor 

 

from runmacs.processor.utils import dthandler, parse_dates_in_tree 

from runmacs.processor.authserver.accesslog import AsyncInfluxDBAccessLogger 

from runmacs.processor.authserver.accesslog import AsyncElasticSearchAccessLogger 

from runmacs.processor.authserver.accesslog import AsyncNullAccessLogger 

from runmacs.processor.authserver.resolver import AsyncResolver 

 

from tornado.web import asynchronous 

 

DEFAULT_REDIRECT = r"/" 

LOCAL_IP_PATTERN = re.compile(r"^10\.153\.(17|52)\.[0-9]+$") 

SCRIPT_USER_AGENTS = map(re.compile, [ 

r"^oc[\.0-9]+$", 

r"^curl/[\.0-9]+$", 

]) 

 

 

class Application(tornado.web.Application): 

""" 

MACSserver authentication server. 

""" 

def __init__(self): 

handlers = [ 

(r"/ping", PingHandler), 

(r"/auth/static/(.*)", 

tornado.web.StaticFileHandler, 

{'path': os.path.join(os.path.dirname(__file__), "static")}), 

(r"/auth/login/?", AuthLoginHandler), 

(r"/auth/logout/?", AuthLogoutHandler), 

(r"/auth/userinfo/?", AuthUserInfoHandler), 

(r"/auth/profile/?", AuthUserProfileHandler), 

(r"/auth/profile/userinfo\.json", 

AuthUserInfoHandler, 

{'fmt': 'json'}), 

(r"/auth/profile/newKey", AuthUserProfileNewKeyHandler), 

(r"/auth/profile/changepass", AuthUserProfileChangePassHandler), 

(r"/auth/profile/key/(?P<key>[0-9a-z\-]+)", 

AuthUserProfileKeyHandler), 

(r"/auth/profile/key/(?P<key>[0-9a-z\-]+)" 

r"/role/(?P<role>[0-9a-zA-Z_]+)", 

AuthUserProfileKeyRoleHandler), 

(r"/auth/user_mgmt/?", AuthUserManagementHandler), 

(r"/auth/user_mgmt/data.json", AuthUserManagementDataHandler), 

(r"/auth/user_mgmt/user/?", UserAdminHandler), 

(r"/auth/user_mgmt/user/(?P<username>[0-9a-z\-_\.]+)", UserAdminHandler), 

(r"(.*)", AuthHandler), 

] 

settings = dict( 

template_path=os.path.join(os.path.dirname(__file__), "templates"), 

static_path=os.path.join(os.path.dirname(__file__), "static"), 

debug=True, 

# cookie_secret="not so good secret", #must be set during startup 

login_url="/auth/login/", 

) 

tornado.web.Application.__init__(self, handlers, **settings) 

 

 

class RequestHandler(tornado.web.RequestHandler): 

""" 

Basic request handler for the authentication server 

""" 

 

def __init__(self, *args, **kwargs): 

super(RequestHandler, self).__init__(*args, **kwargs) 

self.user_coll = self.settings['db'].users 

self.role_coll = self.settings['db'].roles 

self.product_coll = self.settings['pdb'].products 

self.access_logger = self.settings['access_logger'] 

 

def staticFile(self, filename): 

""" 

Generates the path to a static file. 

 

:param filename: name of the file, relative to static file directory 

""" 

return "/auth/static/" + filename 

 

@gen.coroutine 

def toLoginPage(self, next=None): 

""" 

Redirect to login page if not accessed by script 

 

:note: After calling this method, no further data can be sent. 

""" 

self.clear_header('X-Auth-User') 

self.clear_header('X-Auth-Roles') 

self.clear_header('X-Auth-Need-Recheck') 

117 ↛ 118line 117 didn't jump to line 118, because the condition on line 117 was never true if self.is_script_client: 

self.set_header('WWW-Authenticate', 'Basic realm="macsServer"') 

self.set_status(401) 

else: 

121 ↛ 124line 121 didn't jump to line 124, because the condition on line 121 was never false if next is None: 

self.redirect(self.settings['login_url']) 

else: 

self.redirect(self.settings['login_url'] + '?next=' + next) 

125 ↛ 126line 125 didn't jump to line 126, because the condition on line 125 was never true if not self._finished: 

self.finish() 

yield self.logAccess(False) 

 

@gen.coroutine 

def deny(self): 

""" 

Deny the request. 

 

:note: After calling this method, no further data can be sent. 

""" 

self.set_status(403) 

self.clear_header('X-Auth-User') 

self.clear_header('X-Auth-Roles') 

self.clear_header('X-Auth-Need-Recheck') 

140 ↛ 142line 140 didn't jump to line 142, because the condition on line 140 was never false if not self._finished: 

self.finish() 

yield self.logAccess(False) 

 

@gen.coroutine 

def deny_quiet(self): 

""" 

Deny the request, but don't tell the client (i.e. no headers are set) 

 

:note: After calling this method, no further data can be sent. 

""" 

if not self._finished: 

self.finish() 

yield self.logAccess(False) 

 

@gen.coroutine 

def accept(self): 

""" 

Accept the request. 

 

:note: After calling this method, no further data can be sent. 

""" 

if not self._finished: 

self.finish() 

yield self.logAccess(True) 

 

@property 

def user_agent(self): 

return self.request.headers.get('User-Agent', '') 

 

@property 

def is_script_client(self): 

for expr in SCRIPT_USER_AGENTS: 

173 ↛ 174line 173 didn't jump to line 174, because the condition on line 173 was never true if expr.match(self.user_agent) is not None: 

return True 

return False 

 

@property 

def originatingIP(self): 

""" 

The normalized IP address of the requesting client. 

""" 

try: 

return self.request.headers['X-Forwarded-For'] 

except KeyError: 

return self.request.remote_ip 

 

@property 

def isFromLocalNet(self): 

""" 

True if request was originated in the MIM network. 

""" 

return LOCAL_IP_PATTERN.match(self.originatingIP) is not None 

 

_user_info = None 

_current_user = None 

_active_user_roles = None 

_authenticyted_by = None 

current_oid = None 

 

@gen.coroutine 

def authenticate_by_api_key(self, apikey, authmode='apikey'): 

query = {'apikeys.%s' % apikey: {'$exists': True}} 

self._user_info = (yield self.user_coll.find_one(query)) 

if self._user_info is not None: 

self._authenticyted_by = (authmode, apikey) 

self._current_user = self._user_info['name'] 

raise gen.Return(self._current_user) 

 

@gen.coroutine 

def get_current_user(self): 

if self._current_user is not None: 

raise gen.Return(self._current_user) 

try: 

apikey = self.get_argument('key') 

except tornado.web.MissingArgumentError: 

pass 

else: 

current_user = (yield self.authenticate_by_api_key(apikey, 

'apikey')) 

if current_user is not None: 

raise gen.Return(current_user) 

try: 

auth_header = self.request.headers['Authorization'].split() 

except KeyError: 

pass 

else: 

if auth_header[0] == 'Basic' and len(auth_header) == 2: 

auth_token = base64.b64decode(auth_header[1]).split(':')[0] 

current_user = (yield self.authenticate_by_api_key(auth_token, 

'basic_auth_apikey')) 

if current_user is not None: 

raise gen.Return(current_user) 

try: 

self._current_user = tornado.escape.json_decode( 

self.get_secure_cookie("user")) 

except TypeError: 

pass 

else: 

self._authenticyted_by = ('username',) 

raise gen.Return(self._current_user) 

241 ↛ 242line 241 didn't jump to line 242, because the condition on line 241 was never true if self.isFromLocalNet: 

self._current_user = self.originatingIP 

self._authenticyted_by = ('localnet',) 

self._user_info = {'name': self._current_user, 

'roles': ['local'], 

'apikeys': {}} 

raise gen.Return(self._current_user) 

raise gen.Return(None) 

 

@gen.coroutine 

def user_info(self): 

252 ↛ 264line 252 didn't jump to line 264, because the condition on line 252 was never false if self._user_info is None: 

self._user_info = (yield self.user_coll.find_one( 

{'name': (yield self.get_current_user())} 

)) 

256 ↛ 257line 256 didn't jump to line 257, because the condition on line 256 was never true if self._user_info is None: 

self._user_info = {} 

else: 

self._user_info.pop('_id', None) 

if 'roles' not in self._user_info: 

self._user_info['roles'] = [] 

262 ↛ 264line 262 didn't jump to line 264, because the condition on line 262 was never false if 'apikeys' not in self._user_info: 

self._user_info['apikeys'] = {} 

raise gen.Return(self._user_info) 

 

@gen.coroutine 

def user_roles(self): 

if self._active_user_roles is None: 

userInfo = (yield self.user_info()) 

270 ↛ 272line 270 didn't jump to line 272, because the condition on line 270 was never false if self.authmode == 'username': 

self._active_user_roles = userInfo.get('roles', []) 

elif self.authmode in ('apikey', 'basic_auth_apikey'): 

try: 

keys_info = userInfo['apikeys'] 

key_info = keys_info[self._authenticyted_by[1]] 

self._active_user_roles = key_info['roles'] 

except KeyError: 

self._active_user_roles = [] 

elif self.authmode == 'localnet': 

self._active_user_roles = userInfo.get('roles', []) 

else: 

self._active_user_roles = [] 

raise gen.Return(self._active_user_roles) 

 

@gen.coroutine 

def user_rights(self): 

roles = (yield self.user_roles()) 

rights = self.role_coll.find({'name': {'$in': roles}}) 

res = (yield rights.to_list(None)) 

for r in res: 

r.pop('_id', None) 

raise gen.Return(res) 

 

@property 

def authmode(self): 

if self._authenticyted_by is None: 

return None 

else: 

return self._authenticyted_by[0] 

 

@property 

def isAPIUser(self): 

return self.authmode != 'username' 

 

@property 

def isAuthenticatedByLocalNet(self): 

return self.authmode == 'localnet' 

 

@gen.coroutine 

def logAccess(self, authok=True): 

uri = self.request.uri 

uriparts = list(urlparse.urlparse(uri)) 

query = uriparts[4].split('&') 

query = [x if not x.startswith('key=') else 'key=...' for x in query] 

uriparts[4] = '&'.join(query) 

uri = urlparse.urlunparse(uriparts) 

current_user = self._current_user 

318 ↛ 319line 318 didn't jump to line 319, because the condition on line 318 was never true if current_user == self.originatingIP: 

try: 

resolver = AsyncResolver() 

current_user = (yield resolver.gethostbyaddr(current_user)) 

except: 

pass 

yield self.access_logger.logAccess(self.originatingIP, 

uri, authok, 

user=current_user, 

authmode=self.authmode, 

oid=self.current_oid, 

method=self.request.method, 

useragent=self.user_agent) 

 

 

class PingHandler(RequestHandler): 

""" 

Handler for pings from varnish liveness checks. 

 

Has to answer, but no content is needed. 

""" 

def get(self): 

pass 

 

 

def compile_regex_list(regex_list): 

out = [] 

for r in regex_list: 

346 ↛ 347line 346 didn't jump to line 347, because the condition on line 346 was never true if len(r) == 0: 

continue 

348 ↛ 350line 348 didn't jump to line 350, because the condition on line 348 was never false if r[0] != '^': 

r = '^' + r 

350 ↛ 352line 350 didn't jump to line 352, because the condition on line 350 was never false if r[-1] != '$': 

r = r + '$' 

out.append(re.compile(r)) 

return out 

 

 

def check_regex_list(regex_list, s): 

return any(r.match(s) is not None for r in regex_list) 

 

 

def find_regex_object(regex_list, s): 

for r in regex_list: 

m = r.match(s) 

if m is None: 

continue 

return m.group('objectId') 

return None 

 

pass_always_pattern = compile_regex_list([r"/", "/help/.*", "/help.html"]) 

pass_recheck_pattern = compile_regex_list([r"/query/?.*", r"/facetInfo/?.*"]) 

check_object_pattern = compile_regex_list( 

[ 

r"/info/(?P<objectId>[0-9a-f]+)\.html", 

r"/whatsmissing/(?P<objectId>[0-9a-f]+)\.html", 

r"/dep/(?P<objectId>[0-9a-f]+)\.svg", 

r"/get/(?P<objectId>[0-9a-f]+)(?:\.(?P<height>[0-9]+))?\.jpg", 

r"/get/(?:(?P<part>[a-zA-Z0-9]+)/)?(?P<objectId>[0-9a-f]+)(?:\.(?P<height>[0-9]+))?\.(?P<filetype>[a-zA-Z0-9]+)", 

r"/dap/(?P<objectId>[0-9a-f]+)\.das", 

r"/dap/(?P<objectId>[0-9a-f]+)\.dds", 

r"/dap/(?P<objectId>[0-9a-f]+)\.dods", 

r"/getCached/(?P<objectId>[0-9a-f]+)(?:\.(?P<height>[0-9]+))?\.jpg", 

r"/getCached/withCoordinates/(?P<objectId>[0-9a-f]+)(?:\.(?P<height>[0-9]+))?\.jpg", 

r"/plot/(?:(?P<part>[a-zA-Z0-9]+)/)?(?P<objectId>[0-9a-f]+)(?:\.(?P<height>[0-9]+))?\.(?P<filetype>[a-zA-Z0-9]+)", 

]) 

 

 

def aggregate_special_rights(rights): 

""" collects all special rights from rights list """ 

special_rights = [] 

for right in rights: 

special_rights += right.get('special', []) 

return set(special_rights) 

 

 

class AuthHandler(RequestHandler): 

""" 

Answers any request with return code representing the uses authentication. 

 

Furthermore, all requests can be logged. 

""" 

 

def set_user_and_roles(self, user, roles): 

self.set_header('X-Auth-User', user) 

self.set_header('X-Auth-Roles', ' '.join(roles)) 

 

def set_recheck(self, do_recheck=True): 

self.set_header('X-Auth-Need-Recheck', 

'True' if do_recheck else 'False') 

 

@asynchronous 

@gen.coroutine 

def get(self, url, method='GET'): 

user = (yield self.get_current_user()) 

if user is None: 

yield self.toLoginPage() 

return 

self.set_user_and_roles(user, (yield self.user_roles())) 

if check_regex_list(pass_always_pattern, url): 

self.set_recheck(False) 

yield self.accept() 

return 

421 ↛ 422line 421 didn't jump to line 422, because the condition on line 421 was never true if check_regex_list(pass_recheck_pattern, url): 

self.set_recheck(True) 

yield self.accept() 

return 

 

oid = find_regex_object(check_object_pattern, url) 

if oid is None: 

yield self.deny() 

return 

self.current_oid = oid # for logging 

 

rights = (yield self.user_rights()) 

special_rights = aggregate_special_rights(rights) 

if 'MIM' in special_rights: 

self.set_recheck(False) 

yield self.accept() 

return 

query_restrictions = [] 

439 ↛ 440line 439 didn't jump to line 440, because the loop on line 439 never started for right in rights: 

try: 

query_restrictions.append(json.loads(right['queryRestriction'])) 

except KeyError: 

continue 

 

445 ↛ 448line 445 didn't jump to line 448, because the condition on line 445 was never false if len(query_restrictions) == 0: 

yield self.deny() 

return 

query = {'_oid': oid, '$or': parse_dates_in_tree(query_restrictions)} 

if (yield self.product_coll.find_one(query, {})) is not None: 

# single products can always be delivered if they pass the check 

self.set_recheck(False) 

yield self.accept() 

return 

yield self.deny() 

return 

 

def put(self, url): 

return self.get(url, 'PUT') 

 

def head(self, url): 

return self.get(url, 'HEAD') 

 

 

class AuthUserInfoHandler(RequestHandler): 

def initialize(self, fmt='html'): 

self.fmt = fmt 

return super(AuthUserInfoHandler, self).initialize() 

 

@gen.coroutine 

def write_html(self): 

user = (yield self.get_current_user()) 

rights = (yield self.user_rights()) 

special_rights = aggregate_special_rights(rights) 

self.set_header('Content-Type', 'text/html') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

self.write('<ul class="userinfo">') 

 

def item(text): 

"""create list element""" 

self.write('<li>%s</li>' % text) 

 

483 ↛ 484line 483 didn't jump to line 484, because the condition on line 483 was never true if user is None: 

item('not logged in') 

item('<a href="/auth/login/">Login</a>') 

else: 

487 ↛ 488line 487 didn't jump to line 488, because the condition on line 487 was never true if self.isAuthenticatedByLocalNet: 

item('access from: %s' % user) 

item('<a href="/help.html">Help</a>') 

item('<a href="/auth/login/">Login</a>') 

else: 

item('logged in as: %s' % user) 

item('<a href="/help.html">Help</a>') 

item('<a href="/auth/logout/">Logout</a>') 

item('<a href="/auth/profile/">Profile settings</a>') 

print special_rights 

if 'ADMIN' in special_rights: 

item('<a href="/auth/user_mgmt/">User management</a>') 

self.write('</ul>') 

 

@gen.coroutine 

def write_json(self): 

userinfo = (yield self.user_info()) 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

 

ui = {'name': userinfo['name'], 

'roles': userinfo['roles'], 

'apikeys': userinfo['apikeys']} 

baseRoles = set(userinfo['roles']) 

512 ↛ 513line 512 didn't jump to line 513 for key, properties in ui['apikeys'].items(): 

properties['addableRoles'] = \ 

sorted(baseRoles - set(properties['roles'])) 

json.dump(ui, self, default=dthandler) 

 

@asynchronous 

@gen.coroutine 

def get(self): 

yield getattr(self, 'write_%s' % self.fmt)() 

 

 

class AuthUserProfileHandler(RequestHandler): 

@asynchronous 

@gen.coroutine 

def get(self): 

user = (yield self.get_current_user()) 

if user is None or self.isAuthenticatedByLocalNet: 

self.toLoginPage('/auth/profile/') 

return 

user_info = (yield self.user_info()) 

self.render('profile.html', 

prefix='', 

staticFile=self.staticFile, 

user_name=user_info['name'], 

user_roles=user_info['roles'], 

user_api_keys=user_info['apikeys']) 

yield self.accept() 

 

 

class AuthUserProfileNewKeyHandler(RequestHandler): 

@asynchronous 

@gen.coroutine 

def post(self): 

user = (yield self.get_current_user()) 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

549 ↛ 550line 549 didn't jump to line 550, because the condition on line 549 was never true if user is None or self.isAuthenticatedByLocalNet: 

json.dump({'error': 'not logged in'}, self) 

yield self.deny_quiet() 

return 

553 ↛ 554line 553 didn't jump to line 554, because the condition on line 553 was never true if self.isAPIUser: 

json.dump({'error': 'cannot modify using API Key'}, self) 

yield self.deny_quiet() 

return 

newKey = str(uuid.uuid4()) 

now = datetime.datetime.utcnow().replace(tzinfo=datetz.tzutc()) 

yield self.user_coll.update({'name': user}, {'$set': {'apikeys.%s'%newKey: {'roles': [], 'created': now}}}) 

json.dump({'ok': newKey}, self) 

yield self.accept() 

 

 

class AuthUserProfileKeyHandler(RequestHandler): 

@asynchronous 

@gen.coroutine 

def delete(self, key): 

user = (yield self.get_current_user()) 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

if user is None or self.isAuthenticatedByLocalNet: 

json.dump({'error': 'not logged in'}, self) 

yield self.deny_quiet() 

return 

if self.isAPIUser: 

json.dump({'error': 'cannot modify using API Key'}, self) 

yield self.deny_quiet() 

return 

yield self.user_coll.update({'name': user}, {'$unset': {'apikeys.%s'%key: ""}}) 

json.dump({'ok': ''}, self) 

yield self.accept() 

 

 

class AuthUserProfileKeyRoleHandler(RequestHandler): 

@asynchronous 

@gen.coroutine 

def put(self, key, role): 

user = (yield self.get_current_user()) 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

if user is None or self.isAuthenticatedByLocalNet: 

json.dump({'error': 'not logged in'}, self) 

yield self.deny_quiet() 

return 

if self.isAPIUser: 

json.dump({'error': 'cannot modify using API Key'}, self) 

yield self.deny_quiet() 

return 

userinfo = (yield self.user_info()) 

allowedRoles = userinfo['roles'] 

if role not in allowedRoles: 

json.dump({'error': 'role not allowed'}, self) 

yield self.deny_quiet() 

return 

yield self.user_coll.update({'name': user}, {'$addToSet': {'apikeys.%s.roles'%key: role}}) 

json.dump({'ok': ''}, self) 

yield self.accept() 

 

@asynchronous 

@gen.coroutine 

def delete(self, key, role): 

user = (yield self.get_current_user()) 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

if user is None or self.isAuthenticatedByLocalNet: 

json.dump({'error': 'not logged in'}, self) 

yield self.deny_quiet() 

return 

if self.isAPIUser: 

json.dump({'error': 'cannot modify using API Key'}, self) 

yield self.deny_quiet() 

return 

yield self.user_coll.update({'name': user}, 

{'$pullAll': { 

'apikeys.%s.roles' % key: [role] 

}}) 

json.dump({'ok': ''}, self) 

yield self.accept() 

 

 

class AuthUserManagementHandler(RequestHandler): 

@asynchronous 

@gen.coroutine 

def get(self): 

rights = (yield self.user_rights()) 

special_rights = aggregate_special_rights(rights) 

if 'ADMIN' not in special_rights: 

yield self.deny() 

return 

 

self.render('user_mgmt.html', 

prefix='', 

staticFile=self.staticFile) 

yield self.accept() 

 

 

class AuthUserManagementDataHandler(RequestHandler): 

@asynchronous 

@gen.coroutine 

def get(self): 

rights = (yield self.user_rights()) 

special_rights = aggregate_special_rights(rights) 

if 'ADMIN' not in special_rights: 

yield self.deny() 

return 

 

roles = (yield self.role_coll.find().to_list(None)) 

rolenames = set() 

for role in roles: 

role.pop('_id', None) 

rolenames.add(role['name']) 

users = (yield self.user_coll.find().to_list(None)) 

for user in users: 

user.pop('_id', None) 

user.pop('password', None) 

user['addableRoles'] = list(rolenames - set(user.get('roles', []))) 

 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

json.dump({'users': users, 'roles': roles}, self, default=dthandler) 

yield self.accept() 

 

 

class UserAdminHandler(RequestHandler): 

@asynchronous 

@gen.coroutine 

def put(self): 

rights = (yield self.user_rights()) 

special_rights = aggregate_special_rights(rights) 

if 'ADMIN' not in special_rights: 

yield self.deny() 

return 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

data = json.loads(self.request.body) 

new_username = data['username'] 

new_password = data['password'] 

users = (yield self.user_coll.find().to_list(None)) 

if new_username in (user['name'] for user in users): 

json.dump({'error': 'user already exists'}, self) 

yield self.accept() 

return 

hashed_pw = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()) 

yield self.user_coll.insert({'name': new_username, 

'password': hashed_pw, 

'roles': [], 

'apikeys': {}}) 

json.dump({'ok': 'user added'}, self) 

yield self.accept() 

 

@asynchronous 

@gen.coroutine 

def post(self, username): 

rights = (yield self.user_rights()) 

special_rights = aggregate_special_rights(rights) 

if 'ADMIN' not in special_rights: 

yield self.deny() 

return 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

data = json.loads(self.request.body) 

for role in data.get('add_roles', []): 

yield self.user_coll.update({'name': username}, 

{'$addToSet': {'roles': role}}) 

for role in data.get('remove_roles', []): 

yield self.user_coll.update({'name': username}, 

{'$pull': {'roles': role}}) 

 

json.dump({'ok': 'roles modified'}, self) 

yield self.accept() 

 

@asynchronous 

@gen.coroutine 

def delete(self, username): 

rights = (yield self.user_rights()) 

special_rights = aggregate_special_rights(rights) 

if 'ADMIN' not in special_rights: 

yield self.deny() 

return 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

yield self.user_coll.remove({'name': username}) 

json.dump({'ok': 'user deleted'}, self) 

yield self.accept() 

 

 

class NeedPasswordCheckMixin(object): 

@gen.coroutine 

def check_permission(self, password, username): 

user_info = (yield self.user_coll.find_one({'name': username})) 

748 ↛ 749line 748 didn't jump to line 749, because the condition on line 748 was never true if user_info is None: 

raise gen.Return(False) 

hashed = user_info['password'].encode('utf-8') 

# raise gen.Return(bcrypt.checkpw(password, user_info['password'])) 

pw_valid = (bcrypt.hashpw(password.encode('utf-8'), hashed) == hashed) 

raise gen.Return(pw_valid) 

 

 

class AuthLoginHandler(RequestHandler, NeedPasswordCheckMixin): 

@asynchronous 

@gen.coroutine 

def get(self): 

errormessage = self.get_argument("error", None) 

successmessage = self.get_argument("success", None) 

redirectNext = self.get_argument("next", DEFAULT_REDIRECT) 

if self.current_user: 

self.redirect(redirectNext) 

yield self.accept() 

return 

self.render("login.html", 

redirectNext=redirectNext, 

prefix='', 

staticFile=self.staticFile, 

errormessage=errormessage, 

successmessage=successmessage) 

yield self.accept() 

 

@asynchronous 

@gen.coroutine 

def post(self): 

username = self.get_argument("username", "") 

password = self.get_argument("password", "") 

auth = (yield self.check_permission(password, username)) 

if auth: 

self.set_current_user(username) 

self.redirect(self.get_argument("next", DEFAULT_REDIRECT)) 

self._current_user = username 

else: 

error_msg = u"?error=" + tornado.escape.url_escape("Login incorrect") 

self.redirect(u"/auth/login/" + error_msg) 

yield self.logAccess(auth) 

 

def set_current_user(self, user): 

791 ↛ 794line 791 didn't jump to line 794, because the condition on line 791 was never false if user: 

self.set_secure_cookie("user", tornado.escape.json_encode(user)) 

else: 

self.clear_cookie("user") 

 

 

class AuthLogoutHandler(RequestHandler): 

@asynchronous 

@gen.coroutine 

def get(self): 

self.clear_cookie("user") 

self.redirect("/auth/login?success=Logout successful") 

yield self.accept() 

 

 

class AuthUserProfileChangePassHandler(RequestHandler, NeedPasswordCheckMixin): 

@asynchronous 

@gen.coroutine 

def post(self): 

user = (yield self.get_current_user()) 

if user is None: 

yield self.deny() 

return 

data = json.loads(self.request.body) 

oldpass = data['oldpass'] 

newpass = data['newpass'] 

auth = (yield self.check_permission(oldpass, user)) 

self.set_header('Content-Type', 'application/json') 

self.set_header('Expires', datetime.datetime.now()) 

self.set_header('Cache-Control', 'no-cache') 

if not auth: 

json.dump({'type': 'error', 'error': 'wrong password'}, self) 

yield self.accept() 

return 

if len(newpass) < 8: 

json.dump({'type': 'error', 'error': 'password too short'}, self) 

yield self.accept() 

return 

yield self.user_coll.update({'name': user}, {'$set': {'password': bcrypt.hashpw(newpass.encode('utf-8'), bcrypt.gensalt())}}) 

json.dump({'type': 'ok'}, self) 

yield self.accept() 

return 

 

 

def _main(): 

import tornado.options 

from tornado.options import define, options 

from runmacs.config import loadConfig 

from runmacs.processor.config import config 

 

frontendConfig = loadConfig('frontend') 

 

define("port", default=7778, help="run on the given port", type=int) 

tornado.options.parse_command_line() 

 

application = Application() 

#application.settings['db'] = motor.MotorClient(config['database']['connection']).macsServer_test 

#application.settings['pdb'] = motor.MotorClient(config['database']['connection']).macsServer 

application.settings['db'] = motor.MotorClient(config['database']['connection'])[config['database']['collection']] 

application.settings['pdb'] = motor.MotorClient(config['database']['connection'])[config['database']['collection']] 

application.settings['cookie_secret'] = frontendConfig['cookieSecret'] 

if 'accesslogger' in config: 

alType = config['accesslogger'].get('type', 'influxdb') 

alArgs = config['accesslogger'].copy() 

if 'type' in alArgs: 

del alArgs['type'] 

if alType == 'influxdb': 

AL = AsyncInfluxDBAccessLogger 

elif alType == 'elasticsearch': 

AL = AsyncElasticSearchAccessLogger 

application.settings['access_logger'] = AL(**alArgs) 

else: 

application.settings['access_logger'] = AsyncNullAccessLogger() 

application.listen(options.port) 

tornado.ioloop.IOLoop.instance().start() 

 

 

if __name__ == '__main__': 

_main()