/
user.py
1831 lines (1742 loc) · 103 KB
/
user.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
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Contains the user interface in the Universe class
"""
import glob
import logging
import os
import random
import socket
import urllib
from datetime import datetime, timedelta
from galaxy import eggs
eggs.require( "MarkupSafe" )
from markupsafe import escape
eggs.require('sqlalchemy')
from sqlalchemy import and_, or_, true, func
from galaxy import model
from galaxy import util
from galaxy import web
from galaxy.security.validate_user_input import (transform_publicname,
validate_email,
validate_password,
validate_publicname)
from galaxy.util import biostar, hash_util, docstring_trim, listify
from galaxy.util.json import dumps, loads
from galaxy.web import url_for
from galaxy.web.base.controller import (BaseUIController,
CreatesApiKeysMixin,
CreatesUsersMixin,
UsesFormDefinitionsMixin)
from galaxy.web.form_builder import build_select_field, CheckboxField
from galaxy.web.framework.helpers import grids, time_ago
from galaxy.exceptions import ObjectInvalid
log = logging.getLogger( __name__ )
REQUIRE_LOGIN_TEMPLATE = """
<p>
This %s has been configured such that only users who are logged in may use it.%s
</p>
"""
PASSWORD_RESET_TEMPLATE = """
To reset your Galaxy password for the instance at %s use the following link,
which will expire %s.
%s
If you did not make this request, no action is necessary on your part, though
you may want to notify an administrator.
If you're having trouble using the link when clicking it from email client, you
can also copy and paste it into your browser.
"""
class UserOpenIDGrid( grids.Grid ):
use_panels = False
title = "OpenIDs linked to your account"
model_class = model.UserOpenID
template = '/user/openid_manage.mako'
default_filter = { "openid": "All" }
default_sort_key = "-create_time"
columns = [
grids.TextColumn( "OpenID URL", key="openid", link=( lambda x: dict( action='openid_auth', login_button="Login", openid_url=x.openid if not x.provider else '', openid_provider=x.provider, auto_associate=True ) ) ),
grids.GridColumn( "Created", key="create_time", format=time_ago ),
]
operations = [
grids.GridOperation( "Delete", async_compatible=True ),
]
def build_initial_query( self, trans, **kwd ):
return trans.sa_session.query( self.model_class ).filter( self.model_class.user_id == trans.user.id )
class User( BaseUIController, UsesFormDefinitionsMixin, CreatesUsersMixin, CreatesApiKeysMixin ):
user_openid_grid = UserOpenIDGrid()
installed_len_files = None
@web.expose
def index( self, trans, cntrller, **kwd ):
return trans.fill_template( '/user/index.mako', cntrller=cntrller )
@web.expose
def openid_auth( self, trans, **kwd ):
'''Handles user request to access an OpenID provider'''
if not trans.app.config.enable_openid:
return trans.show_error_message( 'OpenID authentication is not enabled in this instance of Galaxy' )
message = 'Unspecified failure authenticating via OpenID'
openid_url = kwd.get( 'openid_url', '' )
openid_provider = kwd.get( 'openid_provider', '' )
if not openid_provider or openid_url:
openid_provider = trans.app.openid_providers.NO_PROVIDER_ID # empty fields cause validation errors
redirect = kwd.get( 'redirect', '' ).strip()
auto_associate = util.string_as_bool( kwd.get( 'auto_associate', False ) )
use_panels = util.string_as_bool( kwd.get( 'use_panels', False ) )
action = 'login'
consumer = trans.app.openid_manager.get_consumer( trans )
if openid_url:
openid_provider_obj = trans.app.openid_providers.new_provider_from_identifier( openid_url )
else:
openid_provider_obj = trans.app.openid_providers.get( openid_provider )
if not openid_url and openid_provider == trans.app.openid_providers.NO_PROVIDER_ID:
message = 'An OpenID provider was not specified'
elif openid_provider_obj:
if not redirect:
redirect = ' '
process_url = trans.request.base.rstrip( '/' ) + url_for( controller='user', action='openid_process', redirect=redirect, openid_provider=openid_provider, auto_associate=auto_associate ) # None of these values can be empty, or else a verification error will occur
request = None
try:
request = consumer.begin( openid_provider_obj.op_endpoint_url )
if request is None:
message = 'No OpenID services are available at %s' % openid_provider_obj.op_endpoint_url
except Exception, e:
message = 'Failed to begin OpenID authentication: %s' % str( e )
if request is not None:
trans.app.openid_manager.add_sreg( trans, request, required=openid_provider_obj.sreg_required, optional=openid_provider_obj.sreg_optional )
if request.shouldSendRedirect():
redirect_url = request.redirectURL(
trans.request.base, process_url )
trans.app.openid_manager.persist_session( trans, consumer )
return trans.response.send_redirect( redirect_url )
else:
form = request.htmlMarkup( trans.request.base, process_url, form_tag_attrs={'id': 'openid_message', 'target': '_top'} )
trans.app.openid_manager.persist_session( trans, consumer )
return form
return trans.response.send_redirect( url_for( controller='user',
action=action,
redirect=redirect,
use_panels=use_panels,
message=message,
status='error' ) )
@web.expose
def openid_process( self, trans, **kwd ):
'''Handle's response from OpenID Providers'''
if not trans.app.config.enable_openid:
return trans.show_error_message( 'OpenID authentication is not enabled in this instance of Galaxy' )
auto_associate = util.string_as_bool( kwd.get( 'auto_associate', False ) )
action = 'login'
if trans.user:
action = 'openid_manage'
if trans.app.config.support_url is not None:
contact = '<a href="%s">support</a>' % trans.app.config.support_url
else:
contact = 'support'
message = 'Verification failed for an unknown reason. Please contact %s for assistance.' % ( contact )
status = 'error'
consumer = trans.app.openid_manager.get_consumer( trans )
info = consumer.complete( kwd, trans.request.url )
display_identifier = info.getDisplayIdentifier()
redirect = kwd.get( 'redirect', '' ).strip()
openid_provider = kwd.get( 'openid_provider', None )
if info.status == trans.app.openid_manager.FAILURE and display_identifier:
message = "Login via OpenID failed. The technical reason for this follows, please include this message in your email if you need to %s to resolve this problem: %s" % ( contact, info.message )
return trans.response.send_redirect( url_for( controller='user',
action=action,
use_panels=True,
redirect=redirect,
message=message,
status='error' ) )
elif info.status == trans.app.openid_manager.SUCCESS:
if info.endpoint.canonicalID:
display_identifier = info.endpoint.canonicalID
openid_provider_obj = trans.app.openid_providers.get( openid_provider )
user_openid = trans.sa_session.query( trans.app.model.UserOpenID ).filter( trans.app.model.UserOpenID.table.c.openid == display_identifier ).first()
if not openid_provider_obj and user_openid and user_openid.provider:
openid_provider_obj = trans.app.openid_providers.get( user_openid.provider )
if not openid_provider_obj:
openid_provider_obj = trans.app.openid_providers.new_provider_from_identifier( display_identifier )
if not user_openid:
user_openid = trans.app.model.UserOpenID( session=trans.galaxy_session, openid=display_identifier )
if not user_openid.user:
user_openid.session = trans.galaxy_session
if not user_openid.provider and openid_provider:
user_openid.provider = openid_provider
if trans.user:
if user_openid.user and user_openid.user.id != trans.user.id:
message = "The OpenID <strong>%s</strong> is already associated with another Galaxy account, <strong>%s</strong>. Please disassociate it from that account before attempting to associate it with a new account." % ( escape( display_identifier ), escape( user_openid.user.email ) )
if not trans.user.active and trans.app.config.user_activation_on: # Account activation is ON and the user is INACTIVE.
if ( trans.app.config.activation_grace_period != 0 ): # grace period is ON
if self.is_outside_grace_period( trans, trans.user.create_time ): # User is outside the grace period. Login is disabled and he will have the activation email resent.
message, status = self.resend_verification_email( trans, trans.user.email, trans.user.username )
else: # User is within the grace period, let him log in.
pass
else: # Grace period is off. Login is disabled and user will have the activation email resent.
message, status = self.resend_verification_email( trans, trans.user.email, trans.user.username )
elif not user_openid.user or user_openid.user == trans.user:
if openid_provider_obj.id:
user_openid.provider = openid_provider_obj.id
user_openid.session = trans.galaxy_session
if not openid_provider_obj.never_associate_with_user:
if not auto_associate and ( user_openid.user and user_openid.user.id == trans.user.id ):
message = "The OpenID <strong>%s</strong> is already associated with your Galaxy account, <strong>%s</strong>." % ( escape( display_identifier ), escape( trans.user.email ) )
status = "warning"
else:
message = "The OpenID <strong>%s</strong> has been associated with your Galaxy account, <strong>%s</strong>." % ( escape( display_identifier ), escape( trans.user.email ) )
status = "done"
user_openid.user = trans.user
trans.sa_session.add( user_openid )
trans.sa_session.flush()
trans.log_event( "User associated OpenID: %s" % display_identifier )
else:
message = "The OpenID <strong>%s</strong> cannot be used to log into your Galaxy account, but any post authentication actions have been performed." % escape( openid_provider_obj.name )
status = "info"
openid_provider_obj.post_authentication( trans, trans.app.openid_manager, info )
if redirect:
message = '%s<br>Click <a href="%s"><strong>here</strong></a> to return to the page you were previously viewing.' % ( message, escape( self.__get_redirect_url( redirect ) ) )
if redirect and status != "error":
return trans.response.send_redirect( self.__get_redirect_url( redirect ) )
return trans.response.send_redirect( url_for( controller='user',
action='openid_manage',
use_panels=True,
redirect=redirect,
message=message,
status=status ) )
elif user_openid.user:
trans.handle_user_login( user_openid.user )
trans.log_event( "User logged in via OpenID: %s" % display_identifier )
openid_provider_obj.post_authentication( trans, trans.app.openid_manager, info )
if not redirect:
redirect = url_for( '/' )
redirect = self.__get_redirect_url( redirect )
return trans.response.send_redirect( redirect )
trans.sa_session.add( user_openid )
trans.sa_session.flush()
message = "OpenID authentication was successful, but you need to associate your OpenID with a Galaxy account."
sreg_resp = trans.app.openid_manager.get_sreg( info )
try:
sreg_username_name = openid_provider_obj.use_for.get( 'username' )
username = sreg_resp.get( sreg_username_name, '' )
except AttributeError:
username = ''
try:
sreg_email_name = openid_provider_obj.use_for.get( 'email' )
email = sreg_resp.get( sreg_email_name, '' )
except AttributeError:
email = ''
# OpenID success, but user not logged in, and not previously associated
return trans.response.send_redirect( url_for( controller='user',
action='openid_associate',
use_panels=True,
redirect=redirect,
username=username,
email=email,
message=message,
status='warning' ) )
elif info.status == trans.app.openid_manager.CANCEL:
message = "Login via OpenID was cancelled by an action at the OpenID provider's site."
status = "warning"
elif info.status == trans.app.openid_manager.SETUP_NEEDED:
if info.setup_url:
return trans.response.send_redirect( info.setup_url )
else:
message = "Unable to log in via OpenID. Setup at the provider is required before this OpenID can be used. Please visit your provider's site to complete this step."
return trans.response.send_redirect( url_for( controller='user',
action=action,
use_panels=True,
redirect=redirect,
message=message,
status=status ) )
@web.expose
def openid_associate( self, trans, cntrller='user', **kwd ):
'''Associates a user with an OpenID log in'''
if not trans.app.config.enable_openid:
return trans.show_error_message( 'OpenID authentication is not enabled in this instance of Galaxy' )
use_panels = util.string_as_bool( kwd.get( 'use_panels', False ) )
message = escape( kwd.get( 'message', '' ) )
status = kwd.get( 'status', 'done' )
email = kwd.get( 'email', '' )
username = kwd.get( 'username', '' )
redirect = kwd.get( 'redirect', '' ).strip()
params = util.Params( kwd )
is_admin = cntrller == 'admin' and trans.user_is_admin()
openids = trans.galaxy_session.openids
user = None
if not openids:
return trans.show_error_message( 'You have not successfully completed an OpenID authentication in this session. You can do so on the <a href="%s">login</a> page.' % url_for( controller='user', action='login', use_panels=use_panels ) )
elif is_admin:
return trans.show_error_message( 'Associating OpenIDs with accounts cannot be done by administrators.' )
if kwd.get( 'login_button', False ):
message, status, user, success = self.__validate_login( trans, **kwd )
if success:
openid_objs = []
for openid in openids:
openid_provider_obj = trans.app.openid_providers.get( openid.provider )
if not openid_provider_obj or not openid_provider_obj.never_associate_with_user:
openid.user = user
trans.sa_session.add( openid )
trans.log_event( "User associated OpenID: %s" % openid.openid )
if openid_provider_obj and openid_provider_obj.has_post_authentication_actions():
openid_objs.append( openid_provider_obj )
trans.sa_session.flush()
if len( openid_objs ) == 1:
return trans.response.send_redirect( url_for( controller='user', action='openid_auth', openid_provider=openid_objs[0].id, redirect=redirect, auto_associate=True ) )
elif openid_objs:
message = 'You have authenticated with several OpenID providers, please click the following links to execute the post authentication actions. '
message = "%s<br/><ul>" % ( message )
for openid in openid_objs:
message = '%s<li><a href="%s" target="_blank">%s</a></li>' % ( message, url_for( controller='user', action='openid_auth', openid_provider=openid.id, redirect=redirect, auto_associate=True ), openid.name )
message = "%s</ul>" % ( message )
return trans.response.send_redirect( url_for( controller='user',
action='openid_manage',
use_panels=use_panels,
redirect=redirect,
message=message,
status='info' ) )
if redirect:
return trans.response.send_redirect( redirect )
return trans.response.send_redirect( url_for( controller='user',
action='openid_manage',
use_panels=use_panels,
redirect=redirect,
message=message,
status='info' ) )
if kwd.get( 'create_user_button', False ):
password = kwd.get( 'password', '' )
confirm = kwd.get( 'confirm', '' )
subscribe = params.get( 'subscribe', '' )
subscribe_checked = CheckboxField.is_checked( subscribe )
error = ''
if not trans.app.config.allow_user_creation and not trans.user_is_admin():
error = 'User registration is disabled. Please contact your local Galaxy administrator for an account.'
else:
# Check email and password validity
error = self.__validate( trans, params, email, password, confirm, username )
if not error:
# all the values are valid
message, status, user, success = self.__register( trans,
cntrller,
subscribe_checked,
**kwd )
if success:
openid_objs = []
for openid in openids:
openid_provider_obj = trans.app.openid_providers.get( openid.provider )
if not openid_provider_obj:
openid_provider_obj = trans.app.openid_providers.new_provider_from_identifier( openid.identifier )
if not openid_provider_obj.never_associate_with_user:
openid.user = user
trans.sa_session.add( openid )
trans.log_event( "User associated OpenID: %s" % openid.openid )
if openid_provider_obj.has_post_authentication_actions():
openid_objs.append( openid_provider_obj )
trans.sa_session.flush()
if len( openid_objs ) == 1:
return trans.response.send_redirect( url_for( controller='user', action='openid_auth', openid_provider=openid_objs[0].id, redirect=redirect, auto_associate=True ) )
elif openid_objs:
message = 'You have authenticated with several OpenID providers, please click the following links to execute the post authentication actions. '
message = "%s<br/><ul>" % ( message )
for openid in openid_objs:
message = '%s<li><a href="%s" target="_blank">%s</a></li>' % ( message, url_for( controller='user', action='openid_auth', openid_provider=openid.id, redirect=redirect, auto_associate=True ), openid.name )
message = "%s</ul>" % ( message )
return trans.response.send_redirect( url_for( controller='user',
action='openid_manage',
use_panels=True,
redirect=redirect,
message=message,
status='info' ) )
if redirect:
return trans.response.send_redirect( redirect )
return trans.response.send_redirect( url_for( controller='user',
action='openid_manage',
use_panels=use_panels,
redirect=redirect,
message=message,
status='info' ) )
else:
message = error
status = 'error'
if trans.webapp.name == 'galaxy':
user_type_form_definition = self.__get_user_type_form_definition( trans, user=user, **kwd )
user_type_fd_id = params.get( 'user_type_fd_id', 'none' )
if user_type_fd_id == 'none' and user_type_form_definition is not None:
user_type_fd_id = trans.security.encode_id( user_type_form_definition.id )
user_type_fd_id_select_field = self.__build_user_type_fd_id_select_field( trans, selected_value=user_type_fd_id )
widgets = self.__get_widgets( trans, user_type_form_definition, user=user, **kwd )
else:
user_type_fd_id_select_field = None
user_type_form_definition = None
widgets = []
return trans.fill_template( '/user/openid_associate.mako',
cntrller=cntrller,
email=email,
password='',
confirm='',
username=transform_publicname( trans, username ),
header='',
use_panels=use_panels,
redirect=redirect,
refresh_frames=[],
message=message,
status=status,
active_view="user",
subscribe_checked=False,
user_type_fd_id_select_field=user_type_fd_id_select_field,
user_type_form_definition=user_type_form_definition,
widgets=widgets,
openids=openids )
@web.expose
@web.require_login( 'manage OpenIDs' )
def openid_disassociate( self, trans, **kwd ):
'''Disassociates a user with an OpenID'''
if not trans.app.config.enable_openid:
return trans.show_error_message( 'OpenID authentication is not enabled in this instance of Galaxy' )
params = util.Params( kwd )
ids = params.get( 'id', None )
message = params.get( 'message', None )
status = params.get( 'status', None )
use_panels = params.get( 'use_panels', False )
user_openids = []
if not ids:
message = 'You must select at least one OpenID to disassociate from your Galaxy account.'
status = 'error'
else:
ids = util.listify( params.id )
for id in ids:
id = trans.security.decode_id( id )
user_openid = trans.sa_session.query( trans.app.model.UserOpenID ).get( int( id ) )
if not user_openid or ( trans.user.id != user_openid.user_id ):
message = 'The selected OpenID(s) are not associated with your Galaxy account.'
status = 'error'
user_openids = []
break
user_openids.append( user_openid )
if user_openids:
deleted_urls = []
for user_openid in user_openids:
trans.sa_session.delete( user_openid )
deleted_urls.append( user_openid.openid )
trans.sa_session.flush()
for deleted_url in deleted_urls:
trans.log_event( "User disassociated OpenID: %s" % deleted_url )
message = '%s OpenIDs were disassociated from your Galaxy account.' % len( ids )
status = 'done'
return trans.response.send_redirect( url_for( controller='user',
action='openid_manage',
use_panels=use_panels,
message=message,
status=status ) )
@web.expose
@web.require_login( 'manage OpenIDs' )
def openid_manage( self, trans, **kwd ):
'''Manage OpenIDs for user'''
if not trans.app.config.enable_openid:
return trans.show_error_message( 'OpenID authentication is not enabled in this instance of Galaxy' )
use_panels = kwd.get( 'use_panels', False )
if 'operation' in kwd:
operation = kwd['operation'].lower()
if operation == "delete":
return trans.response.send_redirect( url_for( controller='user',
action='openid_disassociate',
use_panels=use_panels,
id=kwd['id'] ) )
kwd['redirect'] = kwd.get( 'redirect', url_for( controller='user', action='openid_manage', use_panels=True ) ).strip()
kwd['openid_providers'] = trans.app.openid_providers
return self.user_openid_grid( trans, **kwd )
@web.expose
def login( self, trans, refresh_frames=[], **kwd ):
'''Handle Galaxy Log in'''
redirect = self.__get_redirect_url( kwd.get( 'redirect', trans.request.referer ).strip() )
redirect_url = '' # always start with redirect_url being empty
use_panels = util.string_as_bool( kwd.get( 'use_panels', False ) )
message = kwd.get( 'message', '' )
status = kwd.get( 'status', 'done' )
header = ''
user = trans.user
login = kwd.get( 'login', '' )
if user:
# Already logged in.
redirect_url = redirect
message = 'You are already logged in.'
status = 'info'
elif kwd.get( 'login_button', False ):
if trans.webapp.name == 'galaxy' and not refresh_frames:
if trans.app.config.require_login:
refresh_frames = [ 'masthead', 'history', 'tools' ]
else:
refresh_frames = [ 'masthead', 'history' ]
message, status, user, success = self.__validate_login( trans, **kwd )
if success:
redirect_url = redirect
if not user and trans.app.config.require_login:
if trans.app.config.allow_user_creation:
create_account_str = " If you don't already have an account, <a href='%s'>you may create one</a>." % \
web.url_for( controller='user', action='create', cntrller='user' )
if trans.webapp.name == 'galaxy':
header = REQUIRE_LOGIN_TEMPLATE % ( "Galaxy instance", create_account_str )
else:
header = REQUIRE_LOGIN_TEMPLATE % ( "Galaxy tool shed", create_account_str )
else:
if trans.webapp.name == 'galaxy':
header = REQUIRE_LOGIN_TEMPLATE % ( "Galaxy instance", "" )
else:
header = REQUIRE_LOGIN_TEMPLATE % ( "Galaxy tool shed", "" )
return trans.fill_template( '/user/login.mako',
login=login,
header=header,
use_panels=use_panels,
redirect_url=redirect_url,
redirect=redirect,
refresh_frames=refresh_frames,
message=message,
status=status,
openid_providers=trans.app.openid_providers,
form_input_auto_focus=True,
active_view="user" )
def __validate_login( self, trans, **kwd ):
"""Validates numerous cases that might happen during the login time."""
status = kwd.get( 'status', 'error' )
login = kwd.get( 'login', '' )
password = kwd.get( 'password', '' )
redirect = kwd.get( 'redirect', trans.request.referer ).strip()
success = False
user = trans.sa_session.query( trans.app.model.User ).filter(or_(
trans.app.model.User.table.c.email == login,
trans.app.model.User.table.c.username == login
)).first()
log.debug("trans.app.config.auth_config_file: %s" % trans.app.config.auth_config_file)
if not user:
autoreg = trans.app.auth_manager.check_auto_registration(trans, login, password)
if autoreg[0]:
kwd['email'] = autoreg[1]
kwd['username'] = autoreg[2]
message = validate_email( trans, kwd['email'] ) # self.__validate( trans, params, email, password, password, username )
if not message:
message, status, user, success = self.__register( trans, 'user', False, **kwd )
if success:
# The handle_user_login() method has a call to the history_set_default_permissions() method
# (needed when logging in with a history), user needs to have default permissions set before logging in
trans.handle_user_login( user )
trans.log_event( "User (auto) created a new account" )
trans.log_event( "User logged in" )
else:
message = "Auto-registration failed, contact your local Galaxy administrator. %s" % message
else:
message = "Auto-registration failed, contact your local Galaxy administrator. %s" % message
else:
message = "No such user or invalid password"
elif user.deleted:
message = "This account has been marked deleted, contact your local Galaxy administrator to restore the account."
if trans.app.config.error_email_to is not None:
message += ' Contact: %s' % trans.app.config.error_email_to
elif user.external:
message = "This account was created for use with an external authentication method, contact your local Galaxy administrator to activate it."
if trans.app.config.error_email_to is not None:
message += ' Contact: %s' % trans.app.config.error_email_to
elif not trans.app.auth_manager.check_password(user, password):
message = "Invalid password"
elif trans.app.config.user_activation_on and not user.active: # activation is ON and the user is INACTIVE
if ( trans.app.config.activation_grace_period != 0 ): # grace period is ON
if self.is_outside_grace_period( trans, user.create_time ): # User is outside the grace period. Login is disabled and he will have the activation email resent.
message, status = self.resend_verification_email( trans, user.email, user.username )
else: # User is within the grace period, let him log in.
message, success, status = self.proceed_login( trans, user, redirect )
else: # Grace period is off. Login is disabled and user will have the activation email resent.
message, status = self.resend_verification_email( trans, user.email, user.username )
else: # activation is OFF
message, success, status = self.proceed_login( trans, user, redirect )
return ( message, status, user, success )
def proceed_login( self, trans, user, redirect ):
"""
Function processes user login. It is called in case all the login requirements are valid.
"""
message = ''
trans.handle_user_login( user )
if trans.webapp.name == 'galaxy':
trans.log_event( "User logged in" )
message = 'You are now logged in as %s.<br>You can <a target="_top" href="%s">go back to the page you were visiting</a> or <a target="_top" href="%s">go to the home page</a>.' % \
( user.email, redirect, url_for( '/' ) )
if trans.app.config.require_login:
message += ' <a target="_top" href="%s">Click here</a> to continue to the home page.' % web.url_for( controller="root", action="welcome" )
success = True
status = 'done'
return message, success, status
@web.expose
def resend_verification( self, trans ):
"""
Exposed function for use outside of the class. E.g. when user click on the resend link in the masthead.
"""
message, status = self.resend_verification_email( trans, None, None )
if status == 'done':
return trans.show_ok_message( message )
else:
return trans.show_error_message( message )
def resend_verification_email( self, trans, email, username ):
"""
Function resends the verification email in case user wants to log in with an inactive account or he clicks the resend link.
"""
if email is None: # User is coming from outside registration form, load email from trans
email = trans.user.email
if username is None: # User is coming from outside registration form, load email from trans
username = trans.user.username
is_activation_sent = self.send_verification_email( trans, email, username )
if is_activation_sent:
message = 'This account has not been activated yet. The activation link has been sent again. Please check your email address <b>%s</b> including the spam/trash folder.<br><a target="_top" href="%s">Return to the home page</a>.' % ( escape( email ), url_for( '/' ) )
status = 'error'
else:
message = 'This account has not been activated yet but we are unable to send the activation link. Please contact your local Galaxy administrator.<br><a target="_top" href="%s">Return to the home page</a>.' % url_for( '/' )
status = 'error'
if trans.app.config.error_email_to is not None:
message += '<br>Error contact: %s' % trans.app.config.error_email_to
return message, status
def is_outside_grace_period( self, trans, create_time ):
"""
Function checks whether the user is outside the config-defined grace period for inactive accounts.
"""
# Activation is forced and the user is not active yet. Check the grace period.
activation_grace_period = trans.app.config.activation_grace_period
# Default value is 3 hours.
if activation_grace_period is None:
activation_grace_period = 3
delta = timedelta( hours=int( activation_grace_period ) )
time_difference = datetime.utcnow() - create_time
return ( time_difference > delta or activation_grace_period == 0 )
@web.expose
def logout( self, trans, logout_all=False ):
if trans.webapp.name == 'galaxy':
if trans.app.config.require_login:
refresh_frames = [ 'masthead', 'history', 'tools' ]
else:
refresh_frames = [ 'masthead', 'history' ]
# Since logging an event requires a session, we'll log prior to ending the session
trans.log_event( "User logged out" )
else:
refresh_frames = [ 'masthead' ]
trans.handle_user_logout( logout_all=logout_all )
message = 'You have been logged out.<br>To log in again <a target="_top" href="%s">go to the home page</a>.' % \
( url_for( '/' ) )
if biostar.biostar_logged_in( trans ):
biostar_url = biostar.biostar_logout( trans )
if biostar_url:
# TODO: It would be better if we automatically logged this user out of biostar
message += '<br>To logout of Biostar, please click <a href="%s" target="_blank">here</a>.' % ( biostar_url )
if trans.app.config.use_remote_user and trans.app.config.remote_user_logout_href:
trans.response.send_redirect(trans.app.config.remote_user_logout_href)
else:
return trans.fill_template('/user/logout.mako',
refresh_frames=refresh_frames,
message=message,
status='done',
active_view="user" )
@web.expose
def create( self, trans, cntrller='user', redirect_url='', refresh_frames=[], **kwd ):
params = util.Params( kwd )
# If the honeypot field is not empty we are dealing with a bot.
honeypot_field = params.get( 'bear_field', '' )
if honeypot_field != '':
return trans.show_error_message( "You've been flagged as a possible bot. If you are not, please try registering again and fill the form out carefully. <a target=\"_top\" href=\"%s\">Go to the home page</a>." ) % url_for( '/' )
message = util.restore_text( params.get( 'message', '' ) )
status = params.get( 'status', 'done' )
use_panels = util.string_as_bool( kwd.get( 'use_panels', True ) )
email = util.restore_text( params.get( 'email', '' ) )
# Do not sanitize passwords, so take from kwd
# instead of params ( which were sanitized )
password = kwd.get( 'password', '' )
confirm = kwd.get( 'confirm', '' )
username = util.restore_text( params.get( 'username', '' ) )
subscribe = params.get( 'subscribe', '' )
subscribe_checked = CheckboxField.is_checked( subscribe )
redirect = kwd.get( 'redirect', trans.request.referer ).strip()
is_admin = cntrller == 'admin' and trans.user_is_admin
if not trans.app.config.allow_user_creation and not trans.user_is_admin():
message = 'User registration is disabled. Please contact your local Galaxy administrator for an account.'
if trans.app.config.error_email_to is not None:
message += ' Contact: %s' % trans.app.config.error_email_to
status = 'error'
else:
# check user is allowed to register
message, status = trans.app.auth_manager.check_registration_allowed(email, username, password)
if message == '':
if not refresh_frames:
if trans.webapp.name == 'galaxy':
if trans.app.config.require_login:
refresh_frames = [ 'masthead', 'history', 'tools' ]
else:
refresh_frames = [ 'masthead', 'history' ]
else:
refresh_frames = [ 'masthead' ]
# Create the user, save all the user info and login to Galaxy
if params.get( 'create_user_button', False ):
# Check email and password validity
message = self.__validate( trans, params, email, password, confirm, username )
if not message:
# All the values are valid
message, status, user, success = self.__register( trans,
cntrller,
subscribe_checked,
**kwd )
if trans.webapp.name == 'tool_shed':
redirect_url = url_for( '/' )
if success and not is_admin:
# The handle_user_login() method has a call to the history_set_default_permissions() method
# (needed when logging in with a history), user needs to have default permissions set before logging in
trans.handle_user_login( user )
trans.log_event( "User created a new account" )
trans.log_event( "User logged in" )
if success and is_admin:
message = 'Created new user account (%s)' % escape( user.email )
trans.response.send_redirect( web.url_for( controller='admin',
action='users',
cntrller=cntrller,
message=message,
status=status ) )
else:
status = 'error'
if trans.webapp.name == 'galaxy':
user_type_form_definition = self.__get_user_type_form_definition( trans, user=None, **kwd )
user_type_fd_id = params.get( 'user_type_fd_id', 'none' )
if user_type_fd_id == 'none' and user_type_form_definition is not None:
user_type_fd_id = trans.security.encode_id( user_type_form_definition.id )
user_type_fd_id_select_field = self.__build_user_type_fd_id_select_field( trans, selected_value=user_type_fd_id )
widgets = self.__get_widgets( trans, user_type_form_definition, user=None, **kwd )
# Warning message that is shown on the registration page.
registration_warning_message = trans.app.config.registration_warning_message
else:
user_type_fd_id_select_field = None
user_type_form_definition = None
widgets = []
registration_warning_message = None
return trans.fill_template( '/user/register.mako',
cntrller=cntrller,
email=email,
username=transform_publicname( trans, username ),
subscribe_checked=subscribe_checked,
user_type_fd_id_select_field=user_type_fd_id_select_field,
user_type_form_definition=user_type_form_definition,
widgets=widgets,
use_panels=use_panels,
redirect=redirect,
redirect_url=redirect_url,
refresh_frames=refresh_frames,
registration_warning_message=registration_warning_message,
message=message,
status=status )
def __register( self, trans, cntrller, subscribe_checked, **kwd ):
email = util.restore_text( kwd.get( 'email', '' ) )
password = kwd.get( 'password', '' )
username = util.restore_text( kwd.get( 'username', '' ) )
message = escape( kwd.get( 'message', '' ) )
status = kwd.get( 'status', 'done' )
is_admin = cntrller == 'admin' and trans.user_is_admin()
user = self.create_user( trans=trans, email=email, username=username, password=password )
error = ''
success = True
if trans.webapp.name == 'galaxy':
# Save other information associated with the user, if any
user_info_forms = self.get_all_forms( trans,
filter=dict( deleted=False ),
form_type=trans.app.model.FormDefinition.types.USER_INFO )
# If there are no user forms available then there is nothing to save
if user_info_forms:
user_type_fd_id = kwd.get( 'user_type_fd_id', 'none' )
if user_type_fd_id not in [ 'none' ]:
user_type_form_definition = trans.sa_session.query( trans.app.model.FormDefinition ).get( trans.security.decode_id( user_type_fd_id ) )
values = self.get_form_values( trans, user, user_type_form_definition, **kwd )
form_values = trans.app.model.FormValues( user_type_form_definition, values )
trans.sa_session.add( form_values )
trans.sa_session.flush()
user.values = form_values
trans.sa_session.add( user )
trans.sa_session.flush()
if subscribe_checked:
# subscribe user to email list
if trans.app.config.smtp_server is None:
error = "Now logged in as " + user.email + ". However, subscribing to the mailing list has failed because mail is not configured for this Galaxy instance. <br>Please contact your local Galaxy administrator."
else:
body = 'Join Mailing list.\n'
to = trans.app.config.mailing_join_addr
frm = email
subject = 'Join Mailing List'
try:
util.send_mail( frm, to, subject, body, trans.app.config )
except:
error = "Now logged in as " + user.email + ". However, subscribing to the mailing list has failed."
if not error and not is_admin:
# The handle_user_login() method has a call to the history_set_default_permissions() method
# (needed when logging in with a history), user needs to have default permissions set before logging in
trans.handle_user_login( user )
trans.log_event( "User created a new account" )
trans.log_event( "User logged in" )
elif not error:
trans.response.send_redirect( web.url_for( controller='admin',
action='users',
message='Created new user account (%s)' % user.email,
status=status ) )
if error:
message = error
status = 'error'
success = False
else:
if trans.webapp.name == 'galaxy' and trans.app.config.user_activation_on:
is_activation_sent = self.send_verification_email( trans, email, username )
if is_activation_sent:
message = 'Now logged in as %s.<br>Verification email has been sent to your email address. Please verify it by clicking the activation link in the email.<br>Please check your spam/trash folder in case you cannot find the message.<br><a target="_top" href="%s">Return to the home page.</a>' % ( escape( user.email ), url_for( '/' ) )
success = True
else:
message = 'Unable to send activation email, please contact your local Galaxy administrator.'
if trans.app.config.error_email_to is not None:
message += ' Contact: %s' % trans.app.config.error_email_to
success = False
else: # User activation is OFF, proceed without sending the activation email.
message = 'Now logged in as %s.<br><a target="_top" href="%s">Return to the home page.</a>' % ( escape( user.email ), url_for( '/' ) )
success = True
return ( message, status, user, success )
def send_verification_email( self, trans, email, username ):
"""
Send the verification email containing the activation link to the user's email.
"""
if username is None:
username = trans.user.username
activation_link = self.prepare_activation_link( trans, escape( email ) )
body = ("Hello %s,\n\n"
"In order to complete the activation process for %s begun on %s at %s, please click on the following link to verify your account:\n\n"
"%s \n\n"
"By clicking on the above link and opening a Galaxy account you are also confirming that you have read and agreed to Galaxy's Terms and Conditions for use of this service (%s). This includes a quota limit of one account per user. Attempts to subvert this limit by creating multiple accounts or through any other method may result in termination of all associated accounts and data.\n\n"
"Please contact us if you need help with your account at: %s. You can also browse resources available at: %s. \n\n"
"More about the Galaxy Project can be found at galaxyproject.org\n\n"
"Your Galaxy Team" % (escape( username ), escape( email ),
datetime.utcnow().strftime( "%D"),
trans.request.host, activation_link,
trans.app.config.terms_url,
trans.app.config.error_email_to,
trans.app.config.instance_resource_url))
to = email
frm = trans.app.config.email_from
subject = 'Galaxy Account Activation'
try:
util.send_mail( frm, to, subject, body, trans.app.config )
return True
except:
return False
def prepare_activation_link( self, trans, email ):
"""
Prepare the account activation link for the user.
"""
activation_token = self.get_activation_token( trans, email )
activation_link = url_for( controller='user', action='activate', activation_token=activation_token, email=email, qualified=True )
return activation_link
def get_activation_token( self, trans, email ):
"""
Check for the activation token. Create new activation token and store it in the database if no token found.
"""
user = trans.sa_session.query( trans.app.model.User ).filter( trans.app.model.User.table.c.email == email ).first()
activation_token = user.activation_token
if activation_token is None:
activation_token = hash_util.new_secure_hash( str( random.getrandbits( 256 ) ) )
user.activation_token = activation_token
trans.sa_session.add( user )
trans.sa_session.flush()
return activation_token
@web.expose
def activate( self, trans, **kwd ):
"""
Check whether token fits the user and then activate the user's account.
"""
params = util.Params( kwd, sanitize=False )
email = urllib.unquote( params.get( 'email', None ) )
activation_token = params.get( 'activation_token', None )
if email is None or activation_token is None:
# We don't have the email or activation_token, show error.
return trans.show_error_message( "You are using an invalid activation link. Try to log in and we will send you a new activation email. <br><a href='%s'>Go to login page.</a>" ) % web.url_for( controller="root", action="index" )
else:
# Find the user
user = trans.sa_session.query( trans.app.model.User ).filter( trans.app.model.User.table.c.email == email ).first()
# If the user is active already don't try to activate
if user.active is True:
return trans.show_ok_message( "Your account is already active. Nothing has changed. <br><a href='%s'>Go to login page.</a>" ) % web.url_for( controller='root', action='index' )
if user.activation_token == activation_token:
user.activation_token = None
user.active = True
trans.sa_session.add( user )
trans.sa_session.flush()
return trans.show_ok_message( "Your account has been successfully activated! <br><a href='%s'>Go to login page.</a>" ) % web.url_for( controller='root', action='index' )
else:
# Tokens don't match. Activation is denied.
return trans.show_error_message( "You are using an invalid activation link. Try to log in and we will send you a new activation email. <br><a href='%s'>Go to login page.</a>" ) % web.url_for( controller='root', action='index' )
return
def __get_user_type_form_definition( self, trans, user=None, **kwd ):
params = util.Params( kwd )
if user and user.values:
user_type_fd_id = trans.security.encode_id( user.values.form_definition.id )
else:
user_type_fd_id = params.get( 'user_type_fd_id', 'none' )
if user_type_fd_id not in [ 'none' ]:
user_type_form_definition = trans.sa_session.query( trans.app.model.FormDefinition ).get( trans.security.decode_id( user_type_fd_id ) )
else:
user_type_form_definition = None
return user_type_form_definition
def __get_widgets( self, trans, user_type_form_definition, user=None, **kwd ):
widgets = []
if user_type_form_definition:
if user:
if user.values:
widgets = user_type_form_definition.get_widgets( user=user,
contents=user.values.content,
**kwd )
else:
widgets = user_type_form_definition.get_widgets( None, contents={}, **kwd )
else:
widgets = user_type_form_definition.get_widgets( None, contents={}, **kwd )
return widgets
@web.expose
def manage_user_info( self, trans, cntrller, **kwd ):
'''Manage a user's login, password, public username, type, addresses, etc.'''
params = util.Params( kwd )
user_id = params.get( 'id', None )
if user_id:
user = trans.sa_session.query( trans.app.model.User ).get( trans.security.decode_id( user_id ) )
else:
user = trans.user
if not user:
raise AssertionError("The user id (%s) is not valid" % str( user_id ))
email = util.restore_text( params.get( 'email', user.email ) )
username = util.restore_text( params.get( 'username', '' ) )
if not username:
username = user.username
message = escape( util.restore_text( params.get( 'message', '' ) ) )
status = params.get( 'status', 'done' )
if trans.webapp.name == 'galaxy':
user_type_form_definition = self.__get_user_type_form_definition( trans, user=user, **kwd )
user_type_fd_id = params.get( 'user_type_fd_id', 'none' )
if user_type_fd_id == 'none' and user_type_form_definition is not None:
user_type_fd_id = trans.security.encode_id( user_type_form_definition.id )
user_type_fd_id_select_field = self.__build_user_type_fd_id_select_field( trans, selected_value=user_type_fd_id )
widgets = self.__get_widgets( trans, user_type_form_definition, user=user, **kwd )
# user's addresses
show_filter = util.restore_text( params.get( 'show_filter', 'Active' ) )
if show_filter == 'All':
addresses = [address for address in user.addresses]
elif show_filter == 'Deleted':
addresses = [address for address in user.addresses if address.deleted]
else:
addresses = [address for address in user.addresses if not address.deleted]
user_info_forms = self.get_all_forms( trans,
filter=dict( deleted=False ),
form_type=trans.app.model.FormDefinition.types.USER_INFO )
return trans.fill_template( '/webapps/galaxy/user/manage_info.mako',
cntrller=cntrller,
user=user,
email=email,
username=username,
user_type_fd_id_select_field=user_type_fd_id_select_field,
user_info_forms=user_info_forms,
user_type_form_definition=user_type_form_definition,
user_type_fd_id=user_type_fd_id,
widgets=widgets,
addresses=addresses,
show_filter=show_filter,
message=message,
status=status )
else:
return trans.fill_template( '/webapps/tool_shed/user/manage_info.mako',
cntrller=cntrller,
user=user,
email=email,
username=username,
message=message,
status=status )
# For REMOTE_USER, we need the ability to just edit the username
@web.expose
@web.require_login( "to manage the public name" )
def edit_username( self, trans, cntrller, **kwd ):
params = util.Params( kwd )
is_admin = cntrller == 'admin' and trans.user_is_admin()
message = util.restore_text( params.get( 'message', '' ) )
status = params.get( 'status', 'done' )
user_id = params.get( 'user_id', None )
if user_id and is_admin:
user = trans.sa_session.query( trans.app.model.User ).get( trans.security.decode_id( user_id ) )
else:
user = trans.user
if user and params.get( 'change_username_button', False ):