︙ | | | ︙ | |
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
|
import datetime
import thread
import logging
import sys
import os
import re
import time
import copy
import smtplib
import urllib
import urllib2
import Cookie
import cStringIO
from email import MIMEBase, MIMEMultipart, MIMEText, Encoders, Header, message_from_string
from contenttype import contenttype
from storage import Storage, StorageList, Settings, Messages
from utils import web2py_uuid
from gluon import *
from fileutils import read_file
import serializers
import contrib.simplejson as simplejson
__all__ = ['Mail', 'Auth', 'Recaptcha', 'Crud', 'Service', 'PluginManager', 'fetch', 'geocode', 'prettydate']
logger = logging.getLogger("web2py")
DEFAULT = lambda: None
def callback(actions,form,tablename=None):
if actions:
if tablename and isinstance(actions,dict):
|
<
<
>
<
>
>
>
>
>
>
>
|
>
>
|
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
|
import datetime
import thread
import logging
import sys
import os
import re
import time
import smtplib
import urllib
import urllib2
import Cookie
import cStringIO
from email import MIMEBase, MIMEMultipart, MIMEText, Encoders, Header, message_from_string
from contenttype import contenttype
from storage import Storage, StorageList, Settings, Messages
from utils import web2py_uuid
from fileutils import read_file
from gluon import *
import serializers
try:
import json as json_parser # try stdlib (Python 2.6)
except ImportError:
try:
import simplejson as json_parser # try external module
except:
import contrib.simplejson as json_parser # fallback to pure-Python module
__all__ = ['Mail', 'Auth', 'Recaptcha', 'Crud', 'Service',
'PluginManager', 'fetch', 'geocode', 'prettydate']
### mind there are two loggers here (logger and crud.settings.logger)!
logger = logging.getLogger("web2py")
DEFAULT = lambda: None
def callback(actions,form,tablename=None):
if actions:
if tablename and isinstance(actions,dict):
|
︙ | | | ︙ | |
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
return b
def call_or_redirect(f,*args):
if callable(f):
redirect(f(*args))
else:
redirect(f)
class Mail(object):
"""
Class for configuring and sending emails with alternative text / html
body, multiple attachments and encryption support
Works with SMTP and Google App Engine.
|
>
>
>
>
>
>
>
>
>
|
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
return b
def call_or_redirect(f,*args):
if callable(f):
redirect(f(*args))
else:
redirect(f)
def replace_id(url, form):
if url and not url[0] == '/' and url[:4] != 'http':
# this is here for backward compatibility
return URL(url.replace('[id]', str(form.vars.id)))
elif url:
# this allows http://..../%(id)s/%(name)s/etc.
return url % form.vars
return url
class Mail(object):
"""
Class for configuring and sending emails with alternative text / html
body, multiple attachments and encryption support
Works with SMTP and Google App Engine.
|
︙ | | | ︙ | |
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
|
self,
payload,
filename=None,
content_id=None,
content_type=None,
encoding='utf-8'):
if isinstance(payload, str):
if filename == None:
filename = os.path.basename(payload)
payload = read_file(payload, 'rb')
else:
if filename == None:
raise Exception('Missing attachment name')
payload = payload.read()
filename = filename.encode(encoding)
if content_type == None:
content_type = contenttype(filename)
self.my_filename = filename
self.my_payload = payload
MIMEBase.MIMEBase.__init__(self, *content_type.split('/', 1))
self.set_payload(payload)
self['Content-Disposition'] = 'attachment; filename="%s"' % filename
if content_id != None:
self['Content-Id'] = '<%s>' % content_id.encode(encoding)
Encoders.encode_base64(self)
def __init__(self, server=None, sender=None, login=None, tls=True):
"""
Main Mail object
|
|
|
|
|
|
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
|
self,
payload,
filename=None,
content_id=None,
content_type=None,
encoding='utf-8'):
if isinstance(payload, str):
if filename is None:
filename = os.path.basename(payload)
payload = read_file(payload, 'rb')
else:
if filename is None:
raise Exception('Missing attachment name')
payload = payload.read()
filename = filename.encode(encoding)
if content_type is None:
content_type = contenttype(filename)
self.my_filename = filename
self.my_payload = payload
MIMEBase.MIMEBase.__init__(self, *content_type.split('/', 1))
self.set_payload(payload)
self['Content-Disposition'] = 'attachment; filename="%s"' % filename
if not content_id is None:
self['Content-Id'] = '<%s>' % content_id.encode(encoding)
Encoders.encode_base64(self)
def __init__(self, server=None, sender=None, login=None, tls=True):
"""
Main Mail object
|
︙ | | | ︙ | |
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
|
raise Exception('Target receiver address not specified')
if cc:
if not isinstance(cc, (list, tuple)):
cc = [cc]
if bcc:
if not isinstance(bcc, (list, tuple)):
bcc = [bcc]
if message == None:
text = html = None
elif isinstance(message, (list, tuple)):
text, html = message
elif message.strip().startswith('<html') and message.strip().endswith('</html>'):
text = self.settings.server=='gae' and message or None
html = message
else:
text = message
html = None
if text != None or html != None:
attachment = MIMEMultipart.MIMEMultipart('alternative')
if text != None:
if isinstance(text, basestring):
text = text.decode(encoding).encode('utf-8')
else:
text = text.read().decode(encoding).encode('utf-8')
attachment.attach(MIMEText.MIMEText(text,_charset='utf-8'))
if html != None:
if isinstance(html, basestring):
html = html.decode(encoding).encode('utf-8')
else:
html = html.read().decode(encoding).encode('utf-8')
attachment.attach(MIMEText.MIMEText(html, 'html',_charset='utf-8'))
payload_in.attach(attachment)
if attachments == None:
pass
elif isinstance(attachments, (list, tuple)):
for attachment in attachments:
payload_in.attach(attachment)
else:
payload_in.attach(attachments)
|
|
|
|
|
|
|
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
|
raise Exception('Target receiver address not specified')
if cc:
if not isinstance(cc, (list, tuple)):
cc = [cc]
if bcc:
if not isinstance(bcc, (list, tuple)):
bcc = [bcc]
if message is None:
text = html = None
elif isinstance(message, (list, tuple)):
text, html = message
elif message.strip().startswith('<html') and message.strip().endswith('</html>'):
text = self.settings.server=='gae' and message or None
html = message
else:
text = message
html = None
if not text is None or not html is None:
attachment = MIMEMultipart.MIMEMultipart('alternative')
if not text is None:
if isinstance(text, basestring):
text = text.decode(encoding).encode('utf-8')
else:
text = text.read().decode(encoding).encode('utf-8')
attachment.attach(MIMEText.MIMEText(text,_charset='utf-8'))
if not html is None:
if isinstance(html, basestring):
html = html.decode(encoding).encode('utf-8')
else:
html = html.read().decode(encoding).encode('utf-8')
attachment.attach(MIMEText.MIMEText(html, 'html',_charset='utf-8'))
payload_in.attach(attachment)
if attachments is None:
pass
elif isinstance(attachments, (list, tuple)):
for attachment in attachments:
payload_in.attach(attachment)
else:
payload_in.attach(attachments)
|
︙ | | | ︙ | |
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
|
if cc:
rec.extend(cc)
if bcc:
rec.extend(bcc)
for addr in rec:
c.op_keylist_start(addr,0)
r = c.op_keylist_next()
if r == None:
self.error='No key for [%s]' % addr
return False
recipients.append(r)
try:
# make the encryption
c.op_encrypt(recipients, 1, plain, cipher)
cipher.seek(0,0)
|
|
|
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
|
if cc:
rec.extend(cc)
if bcc:
rec.extend(bcc)
for addr in rec:
c.op_keylist_start(addr,0)
r = c.op_keylist_next()
if r is None:
self.error='No key for [%s]' % addr
return False
recipients.append(r)
try:
# make the encryption
c.op_encrypt(recipients, 1, plain, cipher)
cipher.seek(0,0)
|
︙ | | | ︙ | |
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
|
to.extend(bcc)
payload['Subject'] = encode_header(subject.decode(encoding))
payload['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.gmtime())
result = {}
try:
if self.settings.server == 'logging':
logger.warn('email not sent\n%s\nFrom: %s\nTo: %s\n\n%s\n%s\n' % \
('-'*40,self.settings.sender,
', '.join(to),text or html,'-'*40))
elif self.settings.server == 'gae':
xcc = dict()
if cc:
xcc['cc'] = cc
if bcc:
xcc['bcc'] = bcc
from google.appengine.api import mail
attachments = attachments and [(a.my_filename,a.my_payload) for a in attachments]
if attachments:
result = mail.send_mail(sender=self.settings.sender, to=origTo,
subject=subject, body=text, html=html,
attachments=attachments, **xcc)
elif html:
result = mail.send_mail(sender=self.settings.sender, to=origTo,
subject=subject, body=text, html=html, **xcc)
else:
result = mail.send_mail(sender=self.settings.sender, to=origTo,
subject=subject, body=text, **xcc)
else:
smtp_args = self.settings.server.split(':')
if self.settings.ssl:
server = smtplib.SMTP_SSL(*smtp_args)
else:
server = smtplib.SMTP(*smtp_args)
if self.settings.tls and not self.settings.ssl:
server.ehlo()
server.starttls()
server.ehlo()
if self.settings.login != None:
server.login(*self.settings.login.split(':',1))
result = server.sendmail(self.settings.sender, to, payload.as_string())
server.quit()
except Exception, e:
logger.warn('Mail.send failure:%s' % e)
self.result = result
self.error = e
|
|
|
>
|
|
|
|
|
|
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
|
to.extend(bcc)
payload['Subject'] = encode_header(subject.decode(encoding))
payload['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.gmtime())
result = {}
try:
if self.settings.server == 'logging':
logger.warn('email not sent\n%s\nFrom: %s\nTo: %s\nSubject: %s\n\n%s\n%s\n' % \
('-'*40,self.settings.sender,
subject,
', '.join(to),text or html,'-'*40))
elif self.settings.server == 'gae':
xcc = dict()
if cc:
xcc['cc'] = cc
if bcc:
xcc['bcc'] = bcc
from google.appengine.api import mail
attachments = attachments and [(a.my_filename,a.my_payload) for a in attachments]
if attachments:
result = mail.send_mail(sender=self.settings.sender, to=origTo,
subject=subject, body=text, html=html,
attachments=attachments, **xcc)
elif html:
result = mail.send_mail(sender=self.settings.sender, to=origTo,
subject=subject, body=text, html=html, **xcc)
else:
result = mail.send_mail(sender=self.settings.sender, to=origTo,
subject=subject, body=text, **xcc)
else:
smtp_args = self.settings.server.split(':')
if self.settings.ssl:
server = smtplib.SMTP_SSL(*smtp_args)
else:
server = smtplib.SMTP(*smtp_args)
if self.settings.tls and not self.settings.ssl:
server.ehlo()
server.starttls()
server.ehlo()
if not self.settings.login is None:
server.login(*self.settings.login.split(':',1))
result = server.sendmail(self.settings.sender, to, payload.as_string())
server.quit()
except Exception, e:
logger.warn('Mail.send failure:%s' % e)
self.result = result
self.error = e
|
︙ | | | ︙ | |
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
|
if not self.errors.captcha:
return XML(captcha).xml()
else:
captcha.append(DIV(self.errors['captcha'], _class='error'))
return XML(captcha).xml()
def addrow(form,a,b,c,style,_id,position=-1):
if style == "divs":
form[0].insert(position, DIV(DIV(LABEL(a),_class='w2p_fl'),
DIV(b, _class='w2p_fw'),
DIV(c, _class='w2p_fc'),
_id = _id))
elif style == "table2cols":
form[0].insert(position, TR(LABEL(a),''))
|
|
|
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
|
if not self.errors.captcha:
return XML(captcha).xml()
else:
captcha.append(DIV(self.errors['captcha'], _class='error'))
return XML(captcha).xml()
def addrow(form, a, b, c, style, _id, position=-1):
if style == "divs":
form[0].insert(position, DIV(DIV(LABEL(a),_class='w2p_fl'),
DIV(b, _class='w2p_fw'),
DIV(c, _class='w2p_fc'),
_id = _id))
elif style == "table2cols":
form[0].insert(position, TR(LABEL(a),''))
|
︙ | | | ︙ | |
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
|
Authentication Example::
from contrib.utils import *
mail=Mail()
mail.settings.server='smtp.gmail.com:587'
mail.settings.sender='you@somewhere.com'
mail.settings.login='username:password'
auth=Auth(globals(), db)
auth.settings.mailer=mail
# auth.settings....=...
auth.define_tables()
def authentication():
return dict(form=auth())
exposes:
|
|
|
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
|
Authentication Example::
from contrib.utils import *
mail=Mail()
mail.settings.server='smtp.gmail.com:587'
mail.settings.sender='you@somewhere.com'
mail.settings.login='username:password'
auth=Auth(db)
auth.settings.mailer=mail
# auth.settings....=...
auth.define_tables()
def authentication():
return dict(form=auth())
exposes:
|
︙ | | | ︙ | |
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
|
...
### these are messages that can be customized
...
"""
def url(self, f=None, args=[], vars={}):
return URL(c=self.settings.controller,f=f,args=args,vars=vars)
def __init__(self, environment=None, db=None,
controller='default', cas_provider = None):
"""
auth=Auth(globals(), db)
- environment is there for legacy but unused (awful)
- db has to be the database where to create tables for authentication
"""
## next two lines for backward compatibility
if not db and environment and isinstance(environment,DAL):
db = environment
self.db = db
self.environment = current
request = current.request
|
>
>
>
>
>
>
>
>
>
>
>
|
>
>
|
>
>
>
|
|
|
|
>
>
>
|
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
|
...
### these are messages that can be customized
...
"""
@staticmethod
def get_or_create_key(filename=None):
request = current.request
if not filename:
filename = os.path.join(request.folder,'private','auth.key')
if os.path.exists(filename):
key = open(filename,'r').read().strip()
else:
key = web2py_uuid()
open(filename,'w').write(key)
return key
def url(self, f=None, args=None, vars=None):
if args is None: args=[]
if vars is None: vars={}
return URL(c=self.settings.controller, f=f, args=args, vars=vars)
def here(self):
return URL(args=current.request.args,vars=current.request.vars)
def __init__(self, environment=None, db=None, mailer=True,
hmac_key=None, controller='default', cas_provider=None):
"""
auth=Auth(db)
- environment is there for legacy but unused (awful)
- db has to be the database where to create tables for authentication
- mailer=Mail(...) or None (no mailed) or True (make a mailer)
- hmac_key can be a hmac_key or hmac_key=Auth.get_or_create_key()
- controller (where is the user action?)
- cas_provider (delegate authentication to the URL, CAS2)
"""
## next two lines for backward compatibility
if not db and environment and isinstance(environment,DAL):
db = environment
self.db = db
self.environment = current
request = current.request
|
︙ | | | ︙ | |
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
|
auth.last_visit = request.now
else:
self.user = None
session.auth = None
settings = self.settings = Settings()
# ## what happens after login?
# ## what happens after registration?
settings.hideerror = False
settings.cas_domains = [request.env.http_host]
settings.cas_provider = cas_provider
settings.extra_fields = {}
settings.actions_disabled = []
settings.reset_password_requires_verification = False
settings.registration_requires_verification = False
settings.registration_requires_approval = False
settings.alternate_requires_registration = False
settings.create_user_groups = True
settings.controller = controller
settings.login_url = self.url('user', args='login')
settings.logged_url = self.url('user', args='profile')
settings.download_url = self.url('download')
settings.mailer = None
settings.login_captcha = None
settings.register_captcha = None
settings.retrieve_username_captcha = None
settings.retrieve_password_captcha = None
settings.captcha = None
settings.expiration = 3600 # one hour
settings.long_expiration = 3600*30*24 # one month
|
>
>
>
>
>
>
|
|
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
|
auth.last_visit = request.now
else:
self.user = None
session.auth = None
settings = self.settings = Settings()
# ## what happens after login?
self.next = current.request.vars._next
if isinstance(self.next,(list,tuple)):
self.next = self.next[0]
# ## what happens after registration?
settings.hideerror = False
settings.password_min_length = 4
settings.cas_domains = [request.env.http_host]
settings.cas_provider = cas_provider
settings.extra_fields = {}
settings.actions_disabled = []
settings.reset_password_requires_verification = False
settings.registration_requires_verification = False
settings.registration_requires_approval = False
settings.login_after_registration = False
settings.alternate_requires_registration = False
settings.create_user_groups = True
settings.controller = controller
settings.login_url = self.url('user', args='login')
settings.logged_url = self.url('user', args='profile')
settings.download_url = self.url('download')
settings.mailer = (mailer==True) and Mail() or mailer
settings.login_captcha = None
settings.register_captcha = None
settings.retrieve_username_captcha = None
settings.retrieve_password_captcha = None
settings.captcha = None
settings.expiration = 3600 # one hour
settings.long_expiration = 3600*30*24 # one month
|
︙ | | | ︙ | |
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
|
settings.logout_next = self.url('index')
settings.logout_onlogout = None
settings.register_next = self.url('index')
settings.register_onvalidation = []
settings.register_onaccept = []
settings.register_fields = None
settings.verify_email_next = self.url('user', args='login')
settings.verify_email_onaccept = []
settings.profile_next = self.url('index')
settings.profile_onvalidation = []
settings.profile_onaccept = []
settings.profile_fields = None
settings.retrieve_username_next = self.url('index')
settings.retrieve_password_next = self.url('index')
settings.request_reset_password_next = self.url('user', args='login')
settings.reset_password_next = self.url('user', args='login')
settings.change_password_next = self.url('index')
settings.change_password_onvalidation = []
settings.change_password_onaccept = []
settings.retrieve_password_onvalidation = []
settings.reset_password_onvalidation = []
settings.hmac_key = None
settings.lock_keys = True
# ## these are messages that can be customized
messages = self.messages = Messages(current.T)
messages.login_button = 'Login'
messages.register_button = 'Register'
messages.password_reset_button = 'Request reset password'
messages.password_change_button = 'Change password'
|
>
|
<
|
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
|
settings.logout_next = self.url('index')
settings.logout_onlogout = None
settings.register_next = self.url('index')
settings.register_onvalidation = []
settings.register_onaccept = []
settings.register_fields = None
settings.register_verify_password = True
settings.verify_email_next = self.url('user', args='login')
settings.verify_email_onaccept = []
settings.profile_next = self.url('index')
settings.profile_onvalidation = []
settings.profile_onaccept = []
settings.profile_fields = None
settings.retrieve_username_next = self.url('index')
settings.retrieve_password_next = self.url('index')
settings.request_reset_password_next = self.url('user', args='login')
settings.reset_password_next = self.url('user', args='login')
settings.change_password_next = self.url('index')
settings.change_password_onvalidation = []
settings.change_password_onaccept = []
settings.retrieve_password_onvalidation = []
settings.reset_password_onvalidation = []
settings.hmac_key = hmac_key
settings.lock_keys = True
# ## these are messages that can be customized
messages = self.messages = Messages(current.T)
messages.login_button = 'Login'
messages.register_button = 'Register'
messages.password_reset_button = 'Request reset password'
messages.password_change_button = 'Change password'
|
︙ | | | ︙ | |
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
|
messages.unable_send_email = 'Unable to send email'
messages.invalid_login = 'Invalid login'
messages.invalid_user = 'Invalid user'
messages.invalid_password = 'Invalid password'
messages.is_empty = "Cannot be empty"
messages.mismatched_password = "Password fields don't match"
messages.verify_email = \
'Click on the link http://...verify_email/%(key)s to verify your email'
messages.verify_email_subject = 'Email verification'
messages.username_sent = 'Your username was emailed to you'
messages.new_password_sent = 'A new password was emailed to you'
messages.password_changed = 'Password changed'
messages.retrieve_username = 'Your username is: %(username)s'
messages.retrieve_username_subject = 'Username retrieve'
messages.retrieve_password = 'Your password is: %(password)s'
messages.retrieve_password_subject = 'Password retrieve'
messages.reset_password = \
'Click on the link http://...reset_password/%(key)s to reset your password'
messages.reset_password_subject = 'Password reset'
messages.invalid_reset_password = 'Invalid reset password'
messages.profile_updated = 'Profile updated'
messages.new_password = 'New password'
messages.old_password = 'Old password'
messages.group_description = \
'Group uniquely assigned to user %(id)s'
|
>
>
|
>
>
|
|
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
|
messages.unable_send_email = 'Unable to send email'
messages.invalid_login = 'Invalid login'
messages.invalid_user = 'Invalid user'
messages.invalid_password = 'Invalid password'
messages.is_empty = "Cannot be empty"
messages.mismatched_password = "Password fields don't match"
messages.verify_email = \
'Click on the link http://' + current.request.env.http_host + \
URL('default','user',args=['verify_email']) + \
'/%(key)s to verify your email'
messages.verify_email_subject = 'Email verification'
messages.username_sent = 'Your username was emailed to you'
messages.new_password_sent = 'A new password was emailed to you'
messages.password_changed = 'Password changed'
messages.retrieve_username = 'Your username is: %(username)s'
messages.retrieve_username_subject = 'Username retrieve'
messages.retrieve_password = 'Your password is: %(password)s'
messages.retrieve_password_subject = 'Password retrieve'
messages.reset_password = \
'Click on the link http://' + current.request.env.http_host + \
URL('default','user',args=['reset_password']) + \
'/%(key)s to reset your password'
messages.reset_password_subject = 'Password reset'
messages.invalid_reset_password = 'Invalid reset password'
messages.profile_updated = 'Profile updated'
messages.new_password = 'New password'
messages.old_password = 'Old password'
messages.group_description = \
'Group uniquely assigned to user %(id)s'
|
︙ | | | ︙ | |
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
|
messages.label_reset_password_key = 'Reset Password key'
messages.label_registration_id = 'Registration identifier'
messages.label_role = 'Role'
messages.label_description = 'Description'
messages.label_user_id = 'User ID'
messages.label_group_id = 'Group ID'
messages.label_name = 'Name'
messages.label_table_name = 'Table name'
messages.label_record_id = 'Record ID'
messages.label_time_stamp = 'Timestamp'
messages.label_client_ip = 'Client IP'
messages.label_origin = 'Origin'
messages.label_remember_me = "Remember me (for 30 days)"
messages['T'] = current.T
messages.verify_password_comment = 'please input your password again'
|
|
|
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
|
messages.label_reset_password_key = 'Reset Password key'
messages.label_registration_id = 'Registration identifier'
messages.label_role = 'Role'
messages.label_description = 'Description'
messages.label_user_id = 'User ID'
messages.label_group_id = 'Group ID'
messages.label_name = 'Name'
messages.label_table_name = 'Object or table name'
messages.label_record_id = 'Record ID'
messages.label_time_stamp = 'Timestamp'
messages.label_client_ip = 'Client IP'
messages.label_origin = 'Origin'
messages.label_remember_me = "Remember me (for 30 days)"
messages['T'] = current.T
messages.verify_password_comment = 'please input your password again'
|
︙ | | | ︙ | |
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
|
'reset_password','request_reset_password',
'change_password','profile','groups',
'impersonate','not_authorized'):
return getattr(self,args[0])()
elif args[0]=='cas' and not self.settings.cas_provider:
if args(1) == 'login': return self.cas_login(version=2)
if args(1) == 'validate': return self.cas_validate(version=2)
if args(1) == 'logout': return self.logout()
else:
raise HTTP(404)
def navbar(self,prefix='Welcome',action=None):
request = current.request
T = current.T
if isinstance(prefix,str):
prefix = T(prefix)
if not action:
action=URL(request.application,request.controller,'user')
if prefix:
|
|
>
|
|
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
|
'reset_password','request_reset_password',
'change_password','profile','groups',
'impersonate','not_authorized'):
return getattr(self,args[0])()
elif args[0]=='cas' and not self.settings.cas_provider:
if args(1) == 'login': return self.cas_login(version=2)
if args(1) == 'validate': return self.cas_validate(version=2)
if args(1) == 'logout':
return self.logout(next=request.vars.service or DEFAULT)
else:
raise HTTP(404)
def navbar(self, prefix='Welcome', action=None):
request = current.request
T = current.T
if isinstance(prefix,str):
prefix = T(prefix)
if not action:
action=URL(request.application,request.controller,'user')
if prefix:
|
︙ | | | ︙ | |
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
|
else:
login=A(T('login'),_href=action+'/login')
register=A(T('register'),_href=action+'/register')
retrieve_username=A(T('forgot username?'),
_href=action+'/retrieve_username')
lost_password=A(T('lost password?'),
_href=action+'/request_reset_password')
bar = SPAN('[ ',login,' ]',_class='auth_navbar')
if not 'register' in self.settings.actions_disabled:
bar.insert(2, ' | ')
bar.insert(3, register)
if 'username' in self.settings.table_user.fields() and \
not 'retrieve_username' in self.settings.actions_disabled:
bar.insert(-1, ' | ')
|
|
|
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
|
else:
login=A(T('login'),_href=action+'/login')
register=A(T('register'),_href=action+'/register')
retrieve_username=A(T('forgot username?'),
_href=action+'/retrieve_username')
lost_password=A(T('lost password?'),
_href=action+'/request_reset_password')
bar = SPAN(' [ ',login,' ]',_class='auth_navbar')
if not 'register' in self.settings.actions_disabled:
bar.insert(2, ' | ')
bar.insert(3, register)
if 'username' in self.settings.table_user.fields() and \
not 'retrieve_username' in self.settings.actions_disabled:
bar.insert(-1, ' | ')
|
︙ | | | ︙ | |
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
|
migrate),
fake_migrate=fake_migrate,
format='%(first_name)s %(last_name)s (%(id)s)'))
table.first_name.requires = \
IS_NOT_EMPTY(error_message=self.messages.is_empty)
table.last_name.requires = \
IS_NOT_EMPTY(error_message=self.messages.is_empty)
table[passfield].requires = [CRYPT(key=settings.hmac_key)]
table.email.requires = \
[IS_EMAIL(error_message=self.messages.invalid_email),
IS_NOT_IN_DB(db, table.email)]
table.registration_key.default = ''
settings.table_user = db[settings.table_user_name]
if not settings.table_group_name in db.tables:
table = db.define_table(
|
|
>
>
|
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
|
migrate),
fake_migrate=fake_migrate,
format='%(first_name)s %(last_name)s (%(id)s)'))
table.first_name.requires = \
IS_NOT_EMPTY(error_message=self.messages.is_empty)
table.last_name.requires = \
IS_NOT_EMPTY(error_message=self.messages.is_empty)
table[passfield].requires = [
CRYPT(key=settings.hmac_key,
min_length=self.settings.password_min_length)]
table.email.requires = \
[IS_EMAIL(error_message=self.messages.invalid_email),
IS_NOT_IN_DB(db, table.email)]
table.registration_key.default = ''
settings.table_user = db[settings.table_user_name]
if not settings.table_group_name in db.tables:
table = db.define_table(
|
︙ | | | ︙ | |
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
|
migrate=self.__get_migrate(
settings.table_permission_name, migrate),
fake_migrate=fake_migrate))
table.group_id.requires = IS_IN_DB(db, '%s.id' %
settings.table_group_name,
'%(role)s (%(id)s)')
table.name.requires = IS_NOT_EMPTY(error_message=self.messages.is_empty)
table.table_name.requires = IS_EMPTY_OR(IS_IN_SET(self.db.tables))
table.record_id.requires = IS_INT_IN_RANGE(0, 10 ** 9)
settings.table_permission = db[settings.table_permission_name]
if not settings.table_event_name in db.tables:
table = db.define_table(
settings.table_event_name,
Field('time_stamp', 'datetime',
default=current.request.now,
|
|
|
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
|
migrate=self.__get_migrate(
settings.table_permission_name, migrate),
fake_migrate=fake_migrate))
table.group_id.requires = IS_IN_DB(db, '%s.id' %
settings.table_group_name,
'%(role)s (%(id)s)')
table.name.requires = IS_NOT_EMPTY(error_message=self.messages.is_empty)
#table.table_name.requires = IS_EMPTY_OR(IS_IN_SET(self.db.tables))
table.record_id.requires = IS_INT_IN_RANGE(0, 10 ** 9)
settings.table_permission = db[settings.table_permission_name]
if not settings.table_event_name in db.tables:
table = db.define_table(
settings.table_event_name,
Field('time_stamp', 'datetime',
default=current.request.now,
|
︙ | | | ︙ | |
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
|
settings.login_form = CasAuth(
casversion = 2,
urlbase = settings.cas_provider,
actions=['login','validate','logout'],
maps=maps)
def log_event(self, description, origin='auth'):
"""
usage::
auth.log_event(description='this happened', origin='auth')
"""
if self.is_logged_in():
user_id = self.user.id
else:
user_id = None # user unknown
self.settings.table_event.insert(description=description,
origin=origin, user_id=user_id)
def get_or_create_user(self, keys):
"""
Used for alternate login methods:
If the user exists already then password is updated.
If the user doesn't yet exist, then they are created.
"""
table_user = self.settings.table_user
if 'registration_id' in table_user.fields() and \
'registration_id' in keys:
username = 'registration_id'
elif 'username' in table_user.fields():
username = 'username'
elif 'email' in table_user.fields():
username = 'email'
else:
raise SyntaxError, "user must have username or email"
passfield = self.settings.password_field
user = self.db(table_user[username] == keys[username]).select().first()
keys['registration_key']=''
if user:
user.update_record(**table_user._filter_fields(keys))
else:
if not 'first_name' in keys and 'first_name' in table_user.fields:
keys['first_name'] = keys[username]
|
|
|
>
|
>
|
<
|
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
|
settings.login_form = CasAuth(
casversion = 2,
urlbase = settings.cas_provider,
actions=['login','validate','logout'],
maps=maps)
def log_event(self, description, vars=None, origin='auth'):
"""
usage::
auth.log_event(description='this happened', origin='auth')
"""
if not description:
return
elif self.is_logged_in():
user_id = self.user.id
else:
user_id = None # user unknown
vars = vars or {}
self.settings.table_event.insert(description=description % vars,
origin=origin, user_id=user_id)
def get_or_create_user(self, keys):
"""
Used for alternate login methods:
If the user exists already then password is updated.
If the user doesn't yet exist, then they are created.
"""
table_user = self.settings.table_user
if 'registration_id' in table_user.fields() and \
'registration_id' in keys:
username = 'registration_id'
elif 'username' in table_user.fields():
username = 'username'
elif 'email' in table_user.fields():
username = 'email'
else:
raise SyntaxError, "user must have username or email"
user = self.db(table_user[username] == keys[username]).select().first()
keys['registration_key']=''
if user:
user.update_record(**table_user._filter_fields(keys))
else:
if not 'first_name' in keys and 'first_name' in table_user.fields:
keys['first_name'] = keys[username]
|
︙ | | | ︙ | |
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
|
allow_access()
def cas_onaccept(form, onaccept=onaccept):
if onaccept!=DEFAULT: onaccept(form)
allow_access()
return self.login(next,onvalidation,cas_onaccept,log)
def cas_validate(self,version=2):
request = current.request
db, table = self.db, self.settings.table_cas
current.response.headers['Content-Type']='text'
ticket = table(uuid=request.vars.ticket)
url = request.env.path_info.rsplit('/',1)[0]
if ticket: # and ticket.created_on>request.now-datetime.timedelta(60):
user = self.settings.table_user(ticket.user_id)
fullname = user.first_name+' '+user.last_name
if version==1:
raise HTTP(200,'yes\n%s:%s:%s'%(user.id,user.email,fullname))
# assume version 2
username = user.get('username',user.email)
raise HTTP(200,'<?xml version="1.0" encoding="UTF-8"?>\n'+\
TAG['cas:serviceResponse'](
TAG['cas:authenticationSuccess'](
TAG['cas:user'](username),
*[TAG['cas:'+field.name](user[field.name]) \
for field in self.settings.table_user \
if field.readable]),
**{'_xmlns:cas':'http://www.yale.edu/tp/cas'}).xml())
if version==1:
raise HTTP(200,'no\n')
# assume version 2
raise HTTP(200,'<?xml version="1.0" encoding="UTF-8"?>\n'+\
TAG['cas:serviceResponse'](
TAG['cas:authenticationFailure'](
'Ticket %s not recognized' % ticket,
_code='INVALID TICKET'),
|
|
<
|
|
|
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
|
allow_access()
def cas_onaccept(form, onaccept=onaccept):
if onaccept!=DEFAULT: onaccept(form)
allow_access()
return self.login(next,onvalidation,cas_onaccept,log)
def cas_validate(self, version=2):
request = current.request
db, table = self.db, self.settings.table_cas
current.response.headers['Content-Type']='text'
ticket = table(uuid=request.vars.ticket)
if ticket: # and ticket.created_on>request.now-datetime.timedelta(60):
user = self.settings.table_user(ticket.user_id)
fullname = user.first_name+' '+user.last_name
if version == 1:
raise HTTP(200,'yes\n%s:%s:%s'%(user.id,user.email,fullname))
# assume version 2
username = user.get('username',user.email)
raise HTTP(200,'<?xml version="1.0" encoding="UTF-8"?>\n'+\
TAG['cas:serviceResponse'](
TAG['cas:authenticationSuccess'](
TAG['cas:user'](username),
*[TAG['cas:'+field.name](user[field.name]) \
for field in self.settings.table_user \
if field.readable]),
**{'_xmlns:cas':'http://www.yale.edu/tp/cas'}).xml())
if version == 1:
raise HTTP(200,'no\n')
# assume version 2
raise HTTP(200,'<?xml version="1.0" encoding="UTF-8"?>\n'+\
TAG['cas:serviceResponse'](
TAG['cas:authenticationFailure'](
'Ticket %s not recognized' % ticket,
_code='INVALID TICKET'),
|
︙ | | | ︙ | |
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
|
table_user[username].requires = tmpvalidator
request = current.request
response = current.response
session = current.session
passfield = self.settings.password_field
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.login_next
if onvalidation == DEFAULT:
onvalidation = self.settings.login_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.login_onaccept
if log == DEFAULT:
log = self.messages.login_log
user = None # default
# do we use our own login form, or from a central source?
if self.settings.login_form == self:
form = SQLFORM(
table_user,
fields=[username, passfield],
hidden=dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.login_button,
delete_label=self.messages.delete_label,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
|
>
>
>
>
>
>
>
>
>
>
<
<
|
|
|
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
|
table_user[username].requires = tmpvalidator
request = current.request
response = current.response
session = current.session
passfield = self.settings.password_field
try: table_user[passfield].requires[-1].min_length = 0
except: pass
### use session for federated login
if self.next:
session._auth_next = self.next
elif session._auth_next:
self.next = session._auth_next
### pass
if next == DEFAULT:
next = self.next or self.settings.login_next
if onvalidation == DEFAULT:
onvalidation = self.settings.login_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.login_onaccept
if log == DEFAULT:
log = self.messages.login_log
user = None # default
# do we use our own login form, or from a central source?
if self.settings.login_form == self:
form = SQLFORM(
table_user,
fields=[username, passfield],
hidden = dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.login_button,
delete_label=self.messages.delete_label,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
|
︙ | | | ︙ | |
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
|
)),"",
self.settings.formstyle,
'auth_user_remember__row')
captcha = self.settings.login_captcha or \
(self.settings.login_captcha!=False and self.settings.captcha)
if captcha:
addrow(form, captcha.label, captcha, captcha.comment, self.settings.formstyle,'captcha__row')
accepted_form = False
if form.accepts(request, session,
formname='login', dbio=False,
onvalidation=onvalidation,
hideerror=self.settings.hideerror):
accepted_form = True
# check for username in db
user = self.db(table_user[username] == form.vars[username]).select().first()
if user:
# user in db, check if registration pending or disabled
temp_user = user
if temp_user.registration_key == 'pending':
response.flash = self.messages.registration_pending
return form
elif temp_user.registration_key in ('disabled','blocked'):
response.flash = self.messages.login_disabled
return form
elif temp_user.registration_key!=None and \
temp_user.registration_key.strip():
response.flash = \
self.messages.registration_verifying
return form
# try alternate logins 1st as these have the
# current version of the password
user = None
|
|
>
|
|
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
|
)),"",
self.settings.formstyle,
'auth_user_remember__row')
captcha = self.settings.login_captcha or \
(self.settings.login_captcha!=False and self.settings.captcha)
if captcha:
addrow(form, captcha.label, captcha, captcha.comment,
self.settings.formstyle,'captcha__row')
accepted_form = False
if form.accepts(request, session,
formname='login', dbio=False,
onvalidation=onvalidation,
hideerror=self.settings.hideerror):
accepted_form = True
# check for username in db
user = self.db(table_user[username] == form.vars[username]).select().first()
if user:
# user in db, check if registration pending or disabled
temp_user = user
if temp_user.registration_key == 'pending':
response.flash = self.messages.registration_pending
return form
elif temp_user.registration_key in ('disabled','blocked'):
response.flash = self.messages.login_disabled
return form
elif not temp_user.registration_key is None and \
temp_user.registration_key.strip():
response.flash = \
self.messages.registration_verifying
return form
# try alternate logins 1st as these have the
# current version of the password
user = None
|
︙ | | | ︙ | |
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
|
request.vars[passfield]):
if not self in self.settings.login_methods:
# do not store password in db
form.vars[passfield] = None
user = self.get_or_create_user(form.vars)
break
if not user:
if self.settings.login_failed_log:
self.log_event(self.settings.login_failed_log % request.post_vars)
# invalid login
session.flash = self.messages.invalid_login
redirect(self.url(args=request.args,vars=request.get_vars))
else:
# use a central authentication server
cas = self.settings.login_form
cas_user = cas.get_user()
if cas_user:
cas_user[passfield] = None
user = self.get_or_create_user(table_user._filter_fields(cas_user))
elif hasattr(cas,'login_form'):
return cas.login_form()
else:
# we need to pass through login again before going on
next = self.url('user',args='login',vars=dict(_next=next))
redirect(cas.login_url(next))
# process authenticated users
if user:
user = Storage(table_user._filter_fields(user, id=True))
if log:
self.log_event(log % user)
# process authenticated users
# user wants to be logged in for longer
session.auth = Storage(
user = user,
last_visit = request.now,
expiration = self.settings.long_expiration,
remember = request.vars.has_key("remember"),
hmac_key = web2py_uuid()
)
self.user = user
session.flash = self.messages.logged_in
# how to continue
if self.settings.login_form == self:
if accepted_form:
callback(onaccept,form)
if isinstance(next, (list, tuple)):
# fix issue with 2.6
next = next[0]
if next and not next[0] == '/' and next[:4] != 'http':
next = self.url(next.replace('[id]', str(form.vars.id)))
redirect(next)
table_user[username].requires = old_requires
return form
elif user:
callback(onaccept,None)
redirect(next)
def logout(self, next=DEFAULT, onlogout=DEFAULT, log=DEFAULT):
"""
logout and redirects to login
.. method:: Auth.logout ([next=DEFAULT[, onlogout=DEFAULT[,
log=DEFAULT]]])
"""
if next == DEFAULT:
next = self.settings.logout_next
if onlogout == DEFAULT:
onlogout = self.settings.logout_onlogout
if onlogout:
onlogout(self.user)
if log == DEFAULT:
log = self.messages.logout_log
if log and self.user:
self.log_event(log % self.user)
if self.settings.login_form != self:
cas = self.settings.login_form
cas_user = cas.get_user()
if cas_user:
next = cas.logout_url(next)
current.session.auth = None
current.session.flash = self.messages.logged_out
if next:
redirect(next)
def register(
self,
next=DEFAULT,
onvalidation=DEFAULT,
onaccept=DEFAULT,
log=DEFAULT,
|
|
|
|
>
|
|
<
<
<
<
>
<
<
|
<
<
>
>
|
|
<
<
|
|
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
|
request.vars[passfield]):
if not self in self.settings.login_methods:
# do not store password in db
form.vars[passfield] = None
user = self.get_or_create_user(form.vars)
break
if not user:
self.log_event(self.settings.login_failed_log,
request.post_vars)
# invalid login
session.flash = self.messages.invalid_login
redirect(self.url(args=request.args,vars=request.get_vars))
else:
# use a central authentication server
cas = self.settings.login_form
cas_user = cas.get_user()
if cas_user:
cas_user[passfield] = None
user = self.get_or_create_user(
table_user._filter_fields(cas_user))
elif hasattr(cas,'login_form'):
return cas.login_form()
else:
# we need to pass through login again before going on
next = self.url('user',args='login')
redirect(cas.login_url(next))
# process authenticated users
if user:
user = Storage(table_user._filter_fields(user, id=True))
# process authenticated users
# user wants to be logged in for longer
session.auth = Storage(
user = user,
last_visit = request.now,
expiration = self.settings.long_expiration,
remember = request.vars.has_key("remember"),
hmac_key = web2py_uuid()
)
self.user = user
self.log_event(log, user)
session.flash = self.messages.logged_in
# how to continue
if self.settings.login_form == self:
if accepted_form:
callback(onaccept,form)
next = replace_id(next, form)
redirect(next)
table_user[username].requires = old_requires
return form
elif user:
callback(onaccept,None)
if next == session._auth_next:
del session._auth_next
redirect(next)
def logout(self, next=DEFAULT, onlogout=DEFAULT, log=DEFAULT):
"""
logout and redirects to login
.. method:: Auth.logout ([next=DEFAULT[, onlogout=DEFAULT[,
log=DEFAULT]]])
"""
if next == DEFAULT:
next = self.settings.logout_next
if onlogout == DEFAULT:
onlogout = self.settings.logout_onlogout
if onlogout:
onlogout(self.user)
if log == DEFAULT:
log = self.messages.logout_log
if self.user:
self.log_event(log, self.user)
if self.settings.login_form != self:
cas = self.settings.login_form
cas_user = cas.get_user()
if cas_user:
next = cas.logout_url(next)
current.session.auth = None
current.session.flash = self.messages.logged_out
redirect(next)
def register(
self,
next=DEFAULT,
onvalidation=DEFAULT,
onaccept=DEFAULT,
log=DEFAULT,
|
︙ | | | ︙ | |
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
|
table_user = self.settings.table_user
request = current.request
response = current.response
session = current.session
if self.is_logged_in():
redirect(self.settings.logged_url)
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.register_next
if onvalidation == DEFAULT:
onvalidation = self.settings.register_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.register_onaccept
if log == DEFAULT:
log = self.messages.register_log
passfield = self.settings.password_field
formstyle = self.settings.formstyle
form = SQLFORM(table_user,
fields = self.settings.register_fields,
hidden=dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.register_button,
delete_label=self.messages.delete_label,
formstyle=formstyle,
separator=self.settings.label_separator
)
for i, row in enumerate(form[0].components):
item = row.element('input',_name=passfield)
if item:
form.custom.widget.password_two = \
INPUT(_name="password_two", _type="password",
requires=IS_EXPR('value==%s' % \
repr(request.vars.get(passfield, None)),
error_message=self.messages.mismatched_password))
addrow(form, self.messages.verify_password + ':',
form.custom.widget.password_two,
self.messages.verify_password_comment,
formstyle,
'%s_%s__row' % (table_user, 'password_two'),
position=i+1)
break
captcha = self.settings.register_captcha or self.settings.captcha
if captcha:
addrow(form, captcha.label, captcha, captcha.comment,self.settings.formstyle, 'captcha__row')
table_user.registration_key.default = key = web2py_uuid()
if form.accepts(request, session, formname='register',
onvalidation=onvalidation,hideerror=self.settings.hideerror):
|
<
<
|
|
|
|
>
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
|
table_user = self.settings.table_user
request = current.request
response = current.response
session = current.session
if self.is_logged_in():
redirect(self.settings.logged_url)
if next == DEFAULT:
next = self.next or self.settings.register_next
if onvalidation == DEFAULT:
onvalidation = self.settings.register_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.register_onaccept
if log == DEFAULT:
log = self.messages.register_log
passfield = self.settings.password_field
formstyle = self.settings.formstyle
form = SQLFORM(table_user,
fields = self.settings.register_fields,
hidden = dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.register_button,
delete_label=self.messages.delete_label,
formstyle=formstyle,
separator=self.settings.label_separator
)
if self.settings.register_verify_password:
for i, row in enumerate(form[0].components):
item = row.element('input',_name=passfield)
if item:
form.custom.widget.password_two = \
INPUT(_name="password_two", _type="password",
requires=IS_EXPR(
'value==%s' % \
repr(request.vars.get(passfield, None)),
error_message=self.messages.mismatched_password))
addrow(form, self.messages.verify_password + ':',
form.custom.widget.password_two,
self.messages.verify_password_comment,
formstyle,
'%s_%s__row' % (table_user, 'password_two'),
position=i+1)
break
captcha = self.settings.register_captcha or self.settings.captcha
if captcha:
addrow(form, captcha.label, captcha, captcha.comment,self.settings.formstyle, 'captcha__row')
table_user.registration_key.default = key = web2py_uuid()
if form.accepts(request, session, formname='register',
onvalidation=onvalidation,hideerror=self.settings.hideerror):
|
︙ | | | ︙ | |
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
|
subject=self.messages.verify_email_subject,
message=self.messages.verify_email
% dict(key=key)):
self.db.rollback()
response.flash = self.messages.unable_send_email
return form
session.flash = self.messages.email_sent
elif self.settings.registration_requires_approval:
table_user[form.vars.id] = dict(registration_key='pending')
session.flash = self.messages.registration_pending
else:
table_user[form.vars.id] = dict(registration_key='')
session.flash = self.messages.registration_successful
table_user = self.settings.table_user
if 'username' in table_user.fields:
username = 'username'
else:
username = 'email'
user = self.db(table_user[username] == form.vars[username]).select().first()
user = Storage(table_user._filter_fields(user, id=True))
session.auth = Storage(user=user, last_visit=request.now,
expiration=self.settings.expiration,
hmac_key = web2py_uuid())
self.user = user
session.flash = self.messages.logged_in
if log:
self.log_event(log % form.vars)
callback(onaccept,form)
if not next:
next = self.url(args = request.args)
elif isinstance(next, (list, tuple)): ### fix issue with 2.6
next = next[0]
elif next and not next[0] == '/' and next[:4] != 'http':
next = self.url(next.replace('[id]', str(form.vars.id)))
redirect(next)
return form
def is_logged_in(self):
"""
checks if the user is logged in and returns True/False.
if so user is in auth.user as well as in session.auth.user
|
|
|
>
>
|
<
|
|
|
<
<
|
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
|
subject=self.messages.verify_email_subject,
message=self.messages.verify_email
% dict(key=key)):
self.db.rollback()
response.flash = self.messages.unable_send_email
return form
session.flash = self.messages.email_sent
if self.settings.registration_requires_approval:
table_user[form.vars.id] = dict(registration_key='pending')
session.flash = self.messages.registration_pending
elif (not self.settings.registration_requires_verification or \
self.settings.login_after_registration):
if not self.settings.registration_requires_verification:
table_user[form.vars.id] = dict(registration_key='')
session.flash = self.messages.registration_successful
table_user = self.settings.table_user
if 'username' in table_user.fields:
username = 'username'
else:
username = 'email'
user = self.db(table_user[username] == form.vars[username]).select().first()
user = Storage(table_user._filter_fields(user, id=True))
session.auth = Storage(user=user, last_visit=request.now,
expiration=self.settings.expiration,
hmac_key = web2py_uuid())
self.user = user
session.flash = self.messages.logged_in
self.log_event(log, form.vars)
callback(onaccept,form)
if not next:
next = self.url(args = request.args)
else:
next = replace_id(next, form)
redirect(next)
return form
def is_logged_in(self):
"""
checks if the user is logged in and returns True/False.
if so user is in auth.user as well as in session.auth.user
|
︙ | | | ︙ | |
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
|
redirect(self.settings.login_url)
if self.settings.registration_requires_approval:
user.update_record(registration_key = 'pending')
current.session.flash = self.messages.registration_pending
else:
user.update_record(registration_key = '')
current.session.flash = self.messages.email_verified
if log == DEFAULT:
log = self.messages.verify_email_log
if next == DEFAULT:
next = self.settings.verify_email_next
if onaccept == DEFAULT:
onaccept = self.settings.verify_email_onaccept
if log:
self.log_event(log % user)
callback(onaccept,user)
redirect(next)
def retrieve_username(
self,
next=DEFAULT,
onvalidation=DEFAULT,
|
>
>
>
<
|
|
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
|
redirect(self.settings.login_url)
if self.settings.registration_requires_approval:
user.update_record(registration_key = 'pending')
current.session.flash = self.messages.registration_pending
else:
user.update_record(registration_key = '')
current.session.flash = self.messages.email_verified
# make sure session has same user.registrato_key as db record
if current.session.auth and current.session.auth.user:
current.session.auth.user.registration_key = user.registration_key
if log == DEFAULT:
log = self.messages.verify_email_log
if next == DEFAULT:
next = self.settings.verify_email_next
if onaccept == DEFAULT:
onaccept = self.settings.verify_email_onaccept
self.log_event(log, user)
callback(onaccept,user)
redirect(next)
def retrieve_username(
self,
next=DEFAULT,
onvalidation=DEFAULT,
|
︙ | | | ︙ | |
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
|
session = current.session
captcha = self.settings.retrieve_username_captcha or \
(self.settings.retrieve_username_captcha!=False and self.settings.captcha)
if not self.settings.mailer:
response.flash = self.messages.function_disabled
return ''
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.retrieve_username_next
if onvalidation == DEFAULT:
onvalidation = self.settings.retrieve_username_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.retrieve_username_onaccept
if log == DEFAULT:
log = self.messages.retrieve_username_log
old_requires = table_user.email.requires
table_user.email.requires = [IS_IN_DB(self.db, table_user.email,
error_message=self.messages.invalid_email)]
form = SQLFORM(table_user,
fields=['email'],
hidden=dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.submit_button,
delete_label=self.messages.delete_label,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
if captcha:
|
<
<
|
|
|
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
|
session = current.session
captcha = self.settings.retrieve_username_captcha or \
(self.settings.retrieve_username_captcha!=False and self.settings.captcha)
if not self.settings.mailer:
response.flash = self.messages.function_disabled
return ''
if next == DEFAULT:
next = self.next or self.settings.retrieve_username_next
if onvalidation == DEFAULT:
onvalidation = self.settings.retrieve_username_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.retrieve_username_onaccept
if log == DEFAULT:
log = self.messages.retrieve_username_log
old_requires = table_user.email.requires
table_user.email.requires = [IS_IN_DB(self.db, table_user.email,
error_message=self.messages.invalid_email)]
form = SQLFORM(table_user,
fields=['email'],
hidden = dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.submit_button,
delete_label=self.messages.delete_label,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
if captcha:
|
︙ | | | ︙ | |
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
|
redirect(self.url(args=request.args))
username = user.username
self.settings.mailer.send(to=form.vars.email,
subject=self.messages.retrieve_username_subject,
message=self.messages.retrieve_username
% dict(username=username))
session.flash = self.messages.email_sent
if log:
self.log_event(log % user)
callback(onaccept,form)
if not next:
next = self.url(args = request.args)
elif isinstance(next, (list, tuple)): ### fix issue with 2.6
next = next[0]
elif next and not next[0] == '/' and next[:4] != 'http':
next = self.url(next.replace('[id]', str(form.vars.id)))
redirect(next)
table_user.email.requires = old_requires
return form
def random_password(self):
import string
import random
|
<
|
|
|
<
<
|
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
|
redirect(self.url(args=request.args))
username = user.username
self.settings.mailer.send(to=form.vars.email,
subject=self.messages.retrieve_username_subject,
message=self.messages.retrieve_username
% dict(username=username))
session.flash = self.messages.email_sent
self.log_event(log, user)
callback(onaccept,form)
if not next:
next = self.url(args = request.args)
else:
next = replace_id(next, form)
redirect(next)
table_user.email.requires = old_requires
return form
def random_password(self):
import string
import random
|
︙ | | | ︙ | |
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
|
request = current.request
response = current.response
session = current.session
if not self.settings.mailer:
response.flash = self.messages.function_disabled
return ''
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.retrieve_password_next
if onvalidation == DEFAULT:
onvalidation = self.settings.retrieve_password_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.retrieve_password_onaccept
if log == DEFAULT:
log = self.messages.retrieve_password_log
old_requires = table_user.email.requires
table_user.email.requires = [IS_IN_DB(self.db, table_user.email,
error_message=self.messages.invalid_email)]
form = SQLFORM(table_user,
fields=['email'],
hidden=dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.submit_button,
delete_label=self.messages.delete_label,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
if form.accepts(request, session,
|
<
<
|
|
|
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
|
request = current.request
response = current.response
session = current.session
if not self.settings.mailer:
response.flash = self.messages.function_disabled
return ''
if next == DEFAULT:
next = self.next or self.settings.retrieve_password_next
if onvalidation == DEFAULT:
onvalidation = self.settings.retrieve_password_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.retrieve_password_onaccept
if log == DEFAULT:
log = self.messages.retrieve_password_log
old_requires = table_user.email.requires
table_user.email.requires = [IS_IN_DB(self.db, table_user.email,
error_message=self.messages.invalid_email)]
form = SQLFORM(table_user,
fields=['email'],
hidden = dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.submit_button,
delete_label=self.messages.delete_label,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
if form.accepts(request, session,
|
︙ | | | ︙ | |
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
|
self.settings.mailer.send(to=form.vars.email,
subject=self.messages.retrieve_password_subject,
message=self.messages.retrieve_password \
% dict(password=password)):
session.flash = self.messages.email_sent
else:
session.flash = self.messages.unable_to_send_email
if log:
self.log_event(log % user)
callback(onaccept,form)
if not next:
next = self.url(args = request.args)
elif isinstance(next, (list, tuple)): ### fix issue with 2.6
next = next[0]
elif next and not next[0] == '/' and next[:4] != 'http':
next = self.url(next.replace('[id]', str(form.vars.id)))
redirect(next)
table_user.email.requires = old_requires
return form
def reset_password(
self,
next=DEFAULT,
|
<
|
|
|
<
<
|
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
|
self.settings.mailer.send(to=form.vars.email,
subject=self.messages.retrieve_password_subject,
message=self.messages.retrieve_password \
% dict(password=password)):
session.flash = self.messages.email_sent
else:
session.flash = self.messages.unable_to_send_email
self.log_event(log, user)
callback(onaccept,form)
if not next:
next = self.url(args = request.args)
else:
next = replace_id(next, form)
redirect(next)
table_user.email.requires = old_requires
return form
def reset_password(
self,
next=DEFAULT,
|
︙ | | | ︙ | |
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
|
table_user = self.settings.table_user
request = current.request
# response = current.response
session = current.session
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.reset_password_next
try:
key = request.vars.key or request.args[-1]
t0 = int(key.split('-')[0])
if time.time()-t0 > 60*60*24: raise Exception
user = self.db(table_user.reset_password_key == key).select().first()
if not user: raise Exception
except Exception:
session.flash = self.messages.invalid_reset_password
redirect(next)
passfield = self.settings.password_field
form = SQLFORM.factory(
Field('new_password', 'password',
label=self.messages.new_password,
requires=self.settings.table_user[passfield].requires),
Field('new_password2', 'password',
label=self.messages.verify_password,
requires=[IS_EXPR('value==%s' % repr(request.vars.new_password),
self.messages.mismatched_password)]),
submit_button=self.messages.password_reset_button,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
if form.accepts(request,session,hideerror=self.settings.hideerror):
user.update_record(**{passfield:form.vars.new_password,
'registration_key':'',
'reset_password_key':''})
|
<
<
|
<
>
|
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
|
table_user = self.settings.table_user
request = current.request
# response = current.response
session = current.session
if next == DEFAULT:
next = self.next or self.settings.reset_password_next
try:
key = request.vars.key or request.args[-1]
t0 = int(key.split('-')[0])
if time.time()-t0 > 60*60*24: raise Exception
user = self.db(table_user.reset_password_key == key).select().first()
if not user: raise Exception
except Exception:
session.flash = self.messages.invalid_reset_password
redirect(next)
passfield = self.settings.password_field
form = SQLFORM.factory(
Field('new_password', 'password',
label=self.messages.new_password,
requires=self.settings.table_user[passfield].requires),
Field('new_password2', 'password',
label=self.messages.verify_password,
requires=[IS_EXPR('value==%s' % repr(request.vars.new_password),
self.messages.mismatched_password)]),
submit_button=self.messages.password_reset_button,
hidden = dict(_next=next),
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
if form.accepts(request,session,hideerror=self.settings.hideerror):
user.update_record(**{passfield:form.vars.new_password,
'registration_key':'',
'reset_password_key':''})
|
︙ | | | ︙ | |
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
|
request = current.request
response = current.response
session = current.session
captcha = self.settings.retrieve_password_captcha or \
(self.settings.retrieve_password_captcha!=False and self.settings.captcha)
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.request_reset_password_next
if not self.settings.mailer:
response.flash = self.messages.function_disabled
return ''
if onvalidation == DEFAULT:
onvalidation = self.settings.reset_password_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.reset_password_onaccept
if log == DEFAULT:
log = self.messages.reset_password_log
# old_requires = table_user.email.requires <<< perhaps should be restored
table_user.email.requires = [
IS_EMAIL(error_message=self.messages.invalid_email),
IS_IN_DB(self.db, table_user.email,
error_message=self.messages.invalid_email)]
form = SQLFORM(table_user,
fields=['email'],
hidden=dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.password_reset_button,
delete_label=self.messages.delete_label,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
if captcha:
|
<
<
|
<
<
|
|
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
|
request = current.request
response = current.response
session = current.session
captcha = self.settings.retrieve_password_captcha or \
(self.settings.retrieve_password_captcha!=False and self.settings.captcha)
if next == DEFAULT:
next = self.next or self.settings.request_reset_password_next
if not self.settings.mailer:
response.flash = self.messages.function_disabled
return ''
if onvalidation == DEFAULT:
onvalidation = self.settings.reset_password_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.reset_password_onaccept
if log == DEFAULT:
log = self.messages.reset_password_log
table_user.email.requires = [
IS_EMAIL(error_message=self.messages.invalid_email),
IS_IN_DB(self.db, table_user.email,
error_message=self.messages.invalid_email)]
form = SQLFORM(table_user,
fields=['email'],
hidden = dict(_next=next),
showid=self.settings.showid,
submit_button=self.messages.password_reset_button,
delete_label=self.messages.delete_label,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
if captcha:
|
︙ | | | ︙ | |
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
|
subject=self.messages.reset_password_subject,
message=self.messages.reset_password % \
dict(key=reset_password_key)):
session.flash = self.messages.email_sent
user.update_record(reset_password_key=reset_password_key)
else:
session.flash = self.messages.unable_to_send_email
if log:
self.log_event(log % user)
callback(onaccept,form)
if not next:
next = self.url(args = request.args)
elif isinstance(next, (list, tuple)): ### fix issue with 2.6
next = next[0]
elif next and not next[0] == '/' and next[:4] != 'http':
next = self.url(next.replace('[id]', str(form.vars.id)))
redirect(next)
# old_requires = table_user.email.requires
return form
def retrieve_password(
self,
next=DEFAULT,
|
<
|
|
|
<
<
|
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
|
subject=self.messages.reset_password_subject,
message=self.messages.reset_password % \
dict(key=reset_password_key)):
session.flash = self.messages.email_sent
user.update_record(reset_password_key=reset_password_key)
else:
session.flash = self.messages.unable_to_send_email
self.log_event(log, user)
callback(onaccept,form)
if not next:
next = self.url(args = request.args)
else:
next = replace_id(next, form)
redirect(next)
# old_requires = table_user.email.requires
return form
def retrieve_password(
self,
next=DEFAULT,
|
︙ | | | ︙ | |
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
|
table_user = self.settings.table_user
usern = self.settings.table_user_name
s = db(table_user.id == self.user.id)
request = current.request
session = current.session
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.change_password_next
if onvalidation == DEFAULT:
onvalidation = self.settings.change_password_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.change_password_onaccept
if log == DEFAULT:
log = self.messages.change_password_log
passfield = self.settings.password_field
|
<
<
|
|
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
|
table_user = self.settings.table_user
usern = self.settings.table_user_name
s = db(table_user.id == self.user.id)
request = current.request
session = current.session
if next == DEFAULT:
next = self.next or self.settings.change_password_next
if onvalidation == DEFAULT:
onvalidation = self.settings.change_password_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.change_password_onaccept
if log == DEFAULT:
log = self.messages.change_password_log
passfield = self.settings.password_field
|
︙ | | | ︙ | |
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
|
label=self.messages.new_password,
requires=table_user[passfield].requires),
Field('new_password2', 'password',
label=self.messages.verify_password,
requires=[IS_EXPR('value==%s' % repr(request.vars.new_password),
self.messages.mismatched_password)]),
submit_button=self.messages.password_change_button,
formstyle = self.settings.formstyle,
separator=self.settings.label_separator
)
if form.accepts(request, session,
formname='change_password',
onvalidation=onvalidation,
hideerror=self.settings.hideerror):
d = {passfield: form.vars.new_password}
s.update(**d)
session.flash = self.messages.password_changed
if log:
self.log_event(log % self.user)
callback(onaccept,form)
if not next:
next = self.url(args=request.args)
elif isinstance(next, (list, tuple)): ### fix issue with 2.6
next = next[0]
elif next and not next[0] == '/' and next[:4] != 'http':
next = self.url(next.replace('[id]', str(form.vars.id)))
redirect(next)
return form
def profile(
self,
next=DEFAULT,
onvalidation=DEFAULT,
|
>
<
|
|
|
<
<
|
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
|
label=self.messages.new_password,
requires=table_user[passfield].requires),
Field('new_password2', 'password',
label=self.messages.verify_password,
requires=[IS_EXPR('value==%s' % repr(request.vars.new_password),
self.messages.mismatched_password)]),
submit_button=self.messages.password_change_button,
hidden = dict(_next=next),
formstyle = self.settings.formstyle,
separator=self.settings.label_separator
)
if form.accepts(request, session,
formname='change_password',
onvalidation=onvalidation,
hideerror=self.settings.hideerror):
d = {passfield: form.vars.new_password}
s.update(**d)
session.flash = self.messages.password_changed
self.log_event(log, self.user)
callback(onaccept,form)
if not next:
next = self.url(args=request.args)
else:
next = replace_id(next, form)
redirect(next)
return form
def profile(
self,
next=DEFAULT,
onvalidation=DEFAULT,
|
︙ | | | ︙ | |
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
|
if not self.is_logged_in():
redirect(self.settings.login_url)
passfield = self.settings.password_field
self.settings.table_user[passfield].writable = False
request = current.request
session = current.session
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.profile_next
if onvalidation == DEFAULT:
onvalidation = self.settings.profile_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.profile_onaccept
if log == DEFAULT:
log = self.messages.profile_log
form = SQLFORM(
table_user,
self.user.id,
fields = self.settings.profile_fields,
hidden = dict(_next=next),
showid = self.settings.showid,
submit_button = self.messages.profile_save_button,
delete_label = self.messages.delete_label,
upload = self.settings.download_url,
formstyle = self.settings.formstyle,
separator=self.settings.label_separator
)
if form.accepts(request, session,
formname='profile',
onvalidation=onvalidation,hideerror=self.settings.hideerror):
self.user.update(table_user._filter_fields(form.vars))
session.flash = self.messages.profile_updated
if log:
self.log_event(log % self.user)
callback(onaccept,form)
if not next:
next = self.url(args=request.args)
elif isinstance(next, (list, tuple)): ### fix issue with 2.6
next = next[0]
elif next and not next[0] == '/' and next[:4] != 'http':
next = self.url(next.replace('[id]', str(form.vars.id)))
redirect(next)
return form
def is_impersonating(self):
return current.session.auth.impersonator
def impersonate(self, user_id=DEFAULT):
|
<
<
|
|
<
|
|
|
<
<
|
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
|
if not self.is_logged_in():
redirect(self.settings.login_url)
passfield = self.settings.password_field
self.settings.table_user[passfield].writable = False
request = current.request
session = current.session
if next == DEFAULT:
next = self.next or self.settings.profile_next
if onvalidation == DEFAULT:
onvalidation = self.settings.profile_onvalidation
if onaccept == DEFAULT:
onaccept = self.settings.profile_onaccept
if log == DEFAULT:
log = self.messages.profile_log
form = SQLFORM(
table_user,
self.user.id,
fields = self.settings.profile_fields,
hidden = dict(_next=next),
showid = self.settings.showid,
submit_button = self.messages.profile_save_button,
delete_label = self.messages.delete_label,
upload = self.settings.download_url,
formstyle = self.settings.formstyle,
separator=self.settings.label_separator
)
if form.accepts(request, session,
formname='profile',
onvalidation=onvalidation, hideerror=self.settings.hideerror):
self.user.update(table_user._filter_fields(form.vars))
session.flash = self.messages.profile_updated
self.log_event(log,self.user)
callback(onaccept,form)
if not next:
next = self.url(args=request.args)
else:
next = replace_id(next, form)
redirect(next)
return form
def is_impersonating(self):
return current.session.auth.impersonator
def impersonate(self, user_id=DEFAULT):
|
︙ | | | ︙ | |
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
|
auth.user.update(
self.settings.table_user._filter_fields(user, True))
self.user = auth.user
if self.settings.login_onaccept:
form = Storage(dict(vars=self.user))
self.settings.login_onaccept(form)
log = self.messages.impersonate_log
if log:
self.log_event(log % dict(id=current_id,other_id=auth.user.id))
elif user_id in (0, '0') and self.is_impersonating():
session.clear()
session.update(cPickle.loads(auth.impersonator))
self.user = session.auth.user
if requested_id == DEFAULT and not request.post_vars:
return SQLFORM.factory(Field('user_id','integer'))
return self.user
def groups(self):
"""
displays the groups and their roles for the logged in user
"""
|
<
|
|
|
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
|
auth.user.update(
self.settings.table_user._filter_fields(user, True))
self.user = auth.user
if self.settings.login_onaccept:
form = Storage(dict(vars=self.user))
self.settings.login_onaccept(form)
log = self.messages.impersonate_log
self.log_event(log,dict(id=current_id, other_id=auth.user.id))
elif user_id in (0, '0') and self.is_impersonating():
session.clear()
session.update(cPickle.loads(auth.impersonator))
self.user = session.auth.user
if requested_id == DEFAULT and not request.post_vars:
return SQLFORM.factory(Field('user_id', 'integer'))
return self.user
def groups(self):
"""
displays the groups and their roles for the logged in user
"""
|
︙ | | | ︙ | |
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
|
return None
return table
def not_authorized(self):
"""
you can change the view for this page to make it look as you like
"""
return 'ACCESS DENIED'
def requires(self, condition):
"""
decorator that prevents access to action if not logged in
"""
def decorator(action):
def f(*a, **b):
if self.settings.allow_basic_login_only and not self.basic():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
return call_or_redirect(self.settings.on_failed_authorization)
if not condition:
if current.request.is_restful:
raise HTTP(403,"Not authorized")
if not self.basic() and not self.is_logged_in():
request = current.request
next = URL(r=request,args=request.args,
vars=request.get_vars)
current.session.flash = current.response.flash
return call_or_redirect(
self.settings.on_failed_authentication,
self.settings.login_url + '?_next='+urllib.quote(next))
else:
current.session.flash = self.messages.access_denied
return call_or_redirect(self.settings.on_failed_authorization)
return action(*a, **b)
f.__doc__ = action.__doc__
f.__name__ = action.__name__
f.__dict__.update(action.__dict__)
return f
return decorator
def requires_login(self):
"""
decorator that prevents access to action if not logged in
"""
def decorator(action):
def f(*a, **b):
if self.settings.allow_basic_login_only and not self.basic():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
return call_or_redirect(self.settings.on_failed_authorization)
if not self.basic() and not self.is_logged_in():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
request = current.request
next = URL(r=request,args=request.args,
vars=request.get_vars)
current.session.flash = current.response.flash
return call_or_redirect(
self.settings.on_failed_authentication,
self.settings.login_url + '?_next='+urllib.quote(next)
)
return action(*a, **b)
f.__doc__ = action.__doc__
f.__name__ = action.__name__
f.__dict__.update(action.__dict__)
return f
return decorator
def requires_membership(self, role=None, group_id=None):
"""
decorator that prevents access to action if not logged in or
if user logged in is not a member of group_id.
If role is provided instead of group_id then the
group_id is calculated.
"""
def decorator(action):
def f(*a, **b):
if self.settings.allow_basic_login_only and not self.basic():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
return call_or_redirect(self.settings.on_failed_authorization)
if not self.basic() and not self.is_logged_in():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
request = current.request
next = URL(r=request,args=request.args,
vars=request.get_vars)
current.session.flash = current.response.flash
return call_or_redirect(
self.settings.on_failed_authentication,
self.settings.login_url + '?_next='+urllib.quote(next)
)
if not self.has_membership(group_id=group_id, role=role):
current.session.flash = self.messages.access_denied
return call_or_redirect(self.settings.on_failed_authorization)
return action(*a, **b)
f.__doc__ = action.__doc__
f.__name__ = action.__name__
f.__dict__.update(action.__dict__)
return f
return decorator
def requires_permission(
self,
name,
table_name='',
record_id=0,
):
"""
decorator that prevents access to action if not logged in or
if user logged in is not a member of any group (role) that
has 'name' access to 'table_name', 'record_id'.
"""
def decorator(action):
def f(*a, **b):
if self.settings.allow_basic_login_only and not self.basic():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
return call_or_redirect(self.settings.on_failed_authorization)
if not self.basic() and not self.is_logged_in():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
request = current.request
next = URL(r=request,args=request.args,
vars=request.get_vars)
current.session.flash = current.response.flash
return call_or_redirect(
self.settings.on_failed_authentication,
self.settings.login_url + '?_next='+urllib.quote(next)
)
if not self.has_permission(name, table_name, record_id):
current.session.flash = self.messages.access_denied
return call_or_redirect(self.settings.on_failed_authorization)
return action(*a, **b)
f.__doc__ = action.__doc__
f.__name__ = action.__name__
f.__dict__.update(action.__dict__)
return f
return decorator
def requires_signature(self):
"""
decorator that prevents access to action if not logged in or
if user logged in is not a member of group_id.
If role is provided instead of group_id then the
group_id is calculated.
"""
def decorator(action):
def f(*a, **b):
if self.settings.allow_basic_login_only and not self.basic():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
return call_or_redirect(self.settings.on_failed_authorization)
if not self.basic() and not self.is_logged_in():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
request = current.request
next = URL(r=request,args=request.args,
vars=request.get_vars)
current.session.flash = current.response.flash
return call_or_redirect(
self.settings.on_failed_authentication,
self.settings.login_url + '?_next='+urllib.quote(next)
)
if not URL.verify(current.request,user_signature=True):
current.session.flash = self.messages.access_denied
return call_or_redirect(self.settings.on_failed_authorization)
return action(*a, **b)
f.__doc__ = action.__doc__
f.__name__ = action.__name__
f.__dict__.update(action.__dict__)
return f
return decorator
def add_group(self, role, description=''):
"""
creates a group associated to a role
"""
group_id = self.settings.table_group.insert(role=role,
description=description)
log = self.messages.add_group_log
if log:
self.log_event(log % dict(group_id=group_id, role=role))
return group_id
def del_group(self, group_id):
"""
deletes a group
"""
self.db(self.settings.table_group.id == group_id).delete()
self.db(self.settings.table_membership.group_id
== group_id).delete()
self.db(self.settings.table_permission.group_id
== group_id).delete()
log = self.messages.del_group_log
if log:
self.log_event(log % dict(group_id=group_id))
def id_group(self, role):
"""
returns the group_id of the group specified by the role
"""
rows = self.db(self.settings.table_group.role == role).select()
if not rows:
|
|
>
|
|
|
>
|
|
|
<
|
|
|
|
|
>
|
|
>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
|
|
|
<
|
|
<
|
<
|
<
<
|
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
|
return None
return table
def not_authorized(self):
"""
you can change the view for this page to make it look as you like
"""
if current.request.ajax:
raise HTTP(403,'ACCESS DENIED')
return 'ACCESS DENIED'
def requires(self, condition):
"""
decorator that prevents access to action if not logged in
"""
def decorator(action):
def f(*a, **b):
if self.settings.allow_basic_login_only and not self.basic():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
return call_or_redirect(
self.settings.on_failed_authorization)
if not self.basic() and not self.is_logged_in():
if current.request.is_restful:
raise HTTP(403,"Not authorized")
elif current.request.ajax:
return A('login',_href=self.settings.login_url)
request = current.request
next = self.here()
current.session.flash = current.response.flash
return call_or_redirect(
self.settings.on_failed_authentication,
self.settings.login_url+\
'?_next='+urllib.quote(next))
if not condition:
current.session.flash = self.messages.access_denied
return call_or_redirect(
self.settings.on_failed_authorization)
return action(*a, **b)
f.__doc__ = action.__doc__
f.__name__ = action.__name__
f.__dict__.update(action.__dict__)
return f
return decorator
def requires_login(self):
"""
decorator that prevents access to action if not logged in
"""
return self.requires(self.is_logged_in())
def requires_membership(self, role=None, group_id=None):
"""
decorator that prevents access to action if not logged in or
if user logged in is not a member of group_id.
If role is provided instead of group_id then the
group_id is calculated.
"""
return self.requires(self.has_membership(group_id=group_id, role=role))
def requires_permission(self, name, table_name='', record_id=0):
"""
decorator that prevents access to action if not logged in or
if user logged in is not a member of any group (role) that
has 'name' access to 'table_name', 'record_id'.
"""
return self.requires(self.has_permission(name, table_name, record_id))
def requires_signature(self):
"""
decorator that prevents access to action if not logged in or
if user logged in is not a member of group_id.
If role is provided instead of group_id then the
group_id is calculated.
"""
return self.requires(URL.verify(current.request,user_signature=True))
def add_group(self, role, description=''):
"""
creates a group associated to a role
"""
group_id = self.settings.table_group.insert(
role=role, description=description)
self.log_event(self.messages.add_group_log,
dict(group_id=group_id, role=role))
return group_id
def del_group(self, group_id):
"""
deletes a group
"""
self.db(self.settings.table_group.id == group_id).delete()
self.db(self.settings.table_membership.group_id == group_id).delete()
self.db(self.settings.table_permission.group_id == group_id).delete()
self.log_event(self.messages.del_group_log,dict(group_id=group_id))
def id_group(self, role):
"""
returns the group_id of the group specified by the role
"""
rows = self.db(self.settings.table_group.role == role).select()
if not rows:
|
︙ | | | ︙ | |
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
|
user_id = self.user.id
membership = self.settings.table_membership
if self.db((membership.user_id == user_id)
& (membership.group_id == group_id)).select():
r = True
else:
r = False
log = self.messages.has_membership_log
if log:
self.log_event(log % dict(user_id=user_id,
group_id=group_id, check=r))
return r
def add_membership(self, group_id=None, user_id=None, role=None):
"""
gives user_id membership of group_id or role
if user_id==None than user_id is that of current logged in user
"""
group_id = group_id or self.id_group(role)
try:
group_id = int(group_id)
except:
group_id = self.id_group(group_id) # interpret group_id as a role
if not user_id and self.user:
user_id = self.user.id
membership = self.settings.table_membership
record = membership(user_id = user_id,group_id = group_id)
if record:
return record.id
else:
id = membership.insert(group_id=group_id, user_id=user_id)
log = self.messages.add_membership_log
if log:
self.log_event(log % dict(user_id=user_id,
group_id=group_id))
return id
def del_membership(self, group_id, user_id=None, role=None):
"""
revokes membership from group_id to user_id
if user_id==None than user_id is that of current logged in user
"""
group_id = group_id or self.id_group(role)
if not user_id and self.user:
user_id = self.user.id
membership = self.settings.table_membership
log = self.messages.del_membership_log
if log:
self.log_event(log % dict(user_id=user_id,
group_id=group_id))
return self.db(membership.user_id
== user_id)(membership.group_id
== group_id).delete()
def has_permission(
self,
name='any',
|
|
<
<
|
|
|
<
<
|
|
|
<
<
|
|
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
|
user_id = self.user.id
membership = self.settings.table_membership
if self.db((membership.user_id == user_id)
& (membership.group_id == group_id)).select():
r = True
else:
r = False
self.log_event(self.messages.has_membership_log,
dict(user_id=user_id,group_id=group_id, check=r))
return r
def add_membership(self, group_id=None, user_id=None, role=None):
"""
gives user_id membership of group_id or role
if user is None than user_id is that of current logged in user
"""
group_id = group_id or self.id_group(role)
try:
group_id = int(group_id)
except:
group_id = self.id_group(group_id) # interpret group_id as a role
if not user_id and self.user:
user_id = self.user.id
membership = self.settings.table_membership
record = membership(user_id = user_id,group_id = group_id)
if record:
return record.id
else:
id = membership.insert(group_id=group_id, user_id=user_id)
self.log_event(self.messages.add_membership_log,
dict(user_id=user_id, group_id=group_id))
return id
def del_membership(self, group_id, user_id=None, role=None):
"""
revokes membership from group_id to user_id
if user_id is None than user_id is that of current logged in user
"""
group_id = group_id or self.id_group(role)
if not user_id and self.user:
user_id = self.user.id
membership = self.settings.table_membership
self.log_event(self.messages.del_membership_log,
dict(user_id=user_id,group_id=group_id))
return self.db(membership.user_id
== user_id)(membership.group_id
== group_id).delete()
def has_permission(
self,
name='any',
|
︙ | | | ︙ | |
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
|
== 0).select(permission.group_id)
groups_required = groups_required.union(set([row.group_id
for row in rows]))
if groups.intersection(groups_required):
r = True
else:
r = False
log = self.messages.has_permission_log
if log and user_id:
self.log_event(log % dict(user_id=user_id, name=name,
table_name=table_name, record_id=record_id))
return r
def add_permission(
self,
group_id,
name='any',
table_name='',
record_id=0,
):
"""
gives group_id 'name' access to 'table_name' and 'record_id'
"""
permission = self.settings.table_permission
if group_id == 0:
group_id = self.user_group()
id = permission.insert(group_id=group_id, name=name,
table_name=str(table_name),
record_id=long(record_id))
log = self.messages.add_permission_log
if log:
self.log_event(log % dict(permission_id=id, group_id=group_id,
name=name, table_name=table_name,
record_id=record_id))
return id
def del_permission(
self,
group_id,
name='any',
table_name='',
record_id=0,
):
"""
revokes group_id 'name' access to 'table_name' and 'record_id'
"""
permission = self.settings.table_permission
log = self.messages.del_permission_log
if log:
self.log_event(log % dict(group_id=group_id, name=name,
table_name=table_name, record_id=record_id))
return self.db(permission.group_id == group_id)(permission.name
== name)(permission.table_name
== str(table_name))(permission.record_id
== long(record_id)).delete()
def accessible_query(self, name, table, user_id=None):
"""
returns a query with all accessible records for user_id or
the current logged in user
this method does not work on GAE because uses JOIN and IN
example::
db(auth.accessible_query('read', db.mytable)).select(db.mytable.ALL)
"""
if not user_id:
user_id = self.user.id
if self.has_permission(name, table, 0, user_id):
return table.id > 0
db = self.db
membership = self.settings.table_membership
permission = self.settings.table_permission
return table.id.belongs(db(membership.user_id == user_id)\
(membership.group_id == permission.group_id)\
(permission.name == name)\
(permission.table_name == table)\
._select(permission.record_id))
class Crud(object):
def url(self, f=None, args=[], vars={}):
"""
this should point to the controller that exposes
download and crud
"""
return URL(c=self.settings.controller,f=f,args=args,vars=vars)
def __init__(self, environment, db=None, controller='default'):
self.db = db
if not db and environment and isinstance(environment,DAL):
self.db = environment
elif not db:
raise SyntaxError, "must pass db as first or second argument"
|
>
|
<
|
|
|
<
|
|
|
|
<
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
|
|
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
|
== 0).select(permission.group_id)
groups_required = groups_required.union(set([row.group_id
for row in rows]))
if groups.intersection(groups_required):
r = True
else:
r = False
if user_id:
self.log_event(self.messages.has_permission_log,
dict(user_id=user_id, name=name,
table_name=table_name, record_id=record_id))
return r
def add_permission(
self,
group_id,
name='any',
table_name='',
record_id=0,
):
"""
gives group_id 'name' access to 'table_name' and 'record_id'
"""
permission = self.settings.table_permission
if group_id == 0:
group_id = self.user_group()
id = permission.insert(group_id=group_id, name=name,
table_name=str(table_name),
record_id=long(record_id))
self.log_event(self.messages.add_permission_log,
dict(permission_id=id, group_id=group_id,
name=name, table_name=table_name,
record_id=record_id))
return id
def del_permission(
self,
group_id,
name='any',
table_name='',
record_id=0,
):
"""
revokes group_id 'name' access to 'table_name' and 'record_id'
"""
permission = self.settings.table_permission
self.log_event(self.messages.del_permission_log,
dict(group_id=group_id, name=name,
table_name=table_name, record_id=record_id))
return self.db(permission.group_id == group_id)(permission.name
== name)(permission.table_name
== str(table_name))(permission.record_id
== long(record_id)).delete()
def accessible_query(self, name, table, user_id=None):
"""
returns a query with all accessible records for user_id or
the current logged in user
this method does not work on GAE because uses JOIN and IN
example::
db(auth.accessible_query('read', db.mytable)).select(db.mytable.ALL)
"""
if not user_id:
user_id = self.user_id
if self.has_permission(name, table, 0, user_id):
return table.id > 0
db = self.db
membership = self.settings.table_membership
permission = self.settings.table_permission
return table.id.belongs(db(membership.user_id == user_id)\
(membership.group_id == permission.group_id)\
(permission.name == name)\
(permission.table_name == table)\
._select(permission.record_id))
@staticmethod
def archive(form,archive_table=None,current_record='current_record'):
"""
If you have a table (db.mytable) that needs full revision history you can just do::
form=crud.update(db.mytable,myrecord,onaccept=auth.archive)
or
form=SQLFORM(db.mytable,myrecord).process(onaccept=auth.archive)
crud.archive will define a new table "mytable_archive" and store the
previous record in the newly created table including a reference
to the current record.
If you want to access such table you need to define it yourself in a model::
db.define_table('mytable_archive',
Field('current_record',db.mytable),
db.mytable)
Notice such table includes all fields of db.mytable plus one: current_record.
crud.archive does not timestamp the stored record unless your original table
has a fields like::
db.define_table(...,
Field('saved_on','datetime',
default=request.now,update=request.now,writable=False),
Field('saved_by',auth.user,
default=auth.user_id,update=auth.user_id,writable=False),
there is nothing special about these fields since they are filled before
the record is archived.
If you want to change the archive table name and the name of the reference field
you can do, for example::
db.define_table('myhistory',
Field('parent_record',db.mytable),
db.mytable)
and use it as::
form=crud.update(db.mytable,myrecord,
onaccept=lambda form:crud.archive(form,
archive_table=db.myhistory,
current_record='parent_record'))
"""
old_record = form.record
if not old_record:
return None
table = form.table
if not archive_table:
archive_table_name = '%s_archive' % table
if archive_table_name in table._db:
archive_table = table._db[archive_table_name]
else:
archive_table = table._db.define_table(archive_table_name,
Field(current_record,table),
table)
new_record = {current_record:old_record.id}
for fieldname in archive_table.fields:
if not fieldname in ['id',current_record] and fieldname in old_record:
new_record[fieldname]=old_record[fieldname]
id = archive_table.insert(**new_record)
return id
class Crud(object):
def url(self, f=None, args=None, vars=None):
"""
this should point to the controller that exposes
download and crud
"""
if args is None: args=[]
if vars is None: vars={}
return URL(c=self.settings.controller, f=f, args=args, vars=vars)
def __init__(self, environment, db=None, controller='default'):
self.db = db
if not db and environment and isinstance(environment,DAL):
self.db = environment
elif not db:
raise SyntaxError, "must pass db as first or second argument"
|
︙ | | | ︙ | |
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
|
elif args[0] == 'update':
return self.update(table, args(2))
elif args[0] == 'delete':
return self.delete(table, args(2))
else:
raise HTTP(404)
def log_event(self, message):
if self.settings.logger:
self.settings.logger.log_event(message, 'crud')
def has_permission(self, name, table, record=0):
if not self.settings.auth:
return True
try:
record_id = record.id
except:
record_id = record
return self.settings.auth.has_permission(name, str(table), record_id)
def tables(self):
return TABLE(*[TR(A(name,
_href=self.url(args=('select',name)))) \
for name in self.db.tables])
@staticmethod
def archive(form,archive_table=None,current_record='current_record'):
"""
If you have a table (db.mytable) that needs full revision history you can just do::
form=crud.update(db.mytable,myrecord,onaccept=crud.archive)
crud.archive will define a new table "mytable_archive" and store the
previous record in the newly created table including a reference
to the current record.
If you want to access such table you need to define it yourself in a model::
db.define_table('mytable_archive',
Field('current_record',db.mytable),
db.mytable)
Notice such table includes all fields of db.mytable plus one: current_record.
crud.archive does not timestamp the stored record unless your original table
has a fields like::
db.define_table(...,
Field('saved_on','datetime',
default=request.now,update=request.now,writable=False),
Field('saved_by',auth.user,
default=auth.user_id,update=auth.user_id,writable=False),
there is nothing special about these fields since they are filled before
the record is archived.
If you want to change the archive table name and the name of the reference field
you can do, for example::
db.define_table('myhistory',
Field('parent_record',db.mytable),
db.mytable)
and use it as::
form=crud.update(db.mytable,myrecord,
onaccept=lambda form:crud.archive(form,
archive_table=db.myhistory,
current_record='parent_record'))
"""
old_record = form.record
if not old_record:
return None
table = form.table
if not archive_table:
archive_table_name = '%s_archive' % table
if archive_table_name in table._db:
archive_table = table._db[archive_table_name]
else:
archive_table = table._db.define_table(archive_table_name,
Field(current_record,table),
table)
new_record = {current_record:old_record.id}
for fieldname in archive_table.fields:
if not fieldname in ['id',current_record] and fieldname in old_record:
new_record[fieldname]=old_record[fieldname]
id = archive_table.insert(**new_record)
return id
def update(
self,
table,
record,
next=DEFAULT,
onvalidation=DEFAULT,
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
|
elif args[0] == 'update':
return self.update(table, args(2))
elif args[0] == 'delete':
return self.delete(table, args(2))
else:
raise HTTP(404)
def log_event(self, message, vars):
if self.settings.logger:
self.settings.logger.log_event(message, vars, origin = 'crud')
def has_permission(self, name, table, record=0):
if not self.settings.auth:
return True
try:
record_id = record.id
except:
record_id = record
return self.settings.auth.has_permission(name, str(table), record_id)
def tables(self):
return TABLE(*[TR(A(name,
_href=self.url(args=('select',name)))) \
for name in self.db.tables])
@staticmethod
def archive(form,archive_table=None,current_record='current_record'):
return Auth.archive(form,archive_table=archive_table,
current_record=current_record)
def update(
self,
table,
record,
next=DEFAULT,
onvalidation=DEFAULT,
|
︙ | | | ︙ | |
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
|
table = self.db[table]
try:
record_id = record.id
except:
record_id = record or 0
if record_id and not self.has_permission('update', table, record_id):
redirect(self.settings.auth.settings.on_failed_authorization)
if not record_id \
and not self.has_permission('create', table, record_id):
redirect(self.settings.auth.settings.on_failed_authorization)
request = current.request
response = current.response
session = current.session
if request.extension == 'json' and request.vars.json:
request.vars.update(simplejson.loads(request.vars.json))
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.update_next
if onvalidation == DEFAULT:
onvalidation = self.settings.update_onvalidation
if onaccept == DEFAULT:
|
<
|
|
|
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
|
table = self.db[table]
try:
record_id = record.id
except:
record_id = record or 0
if record_id and not self.has_permission('update', table, record_id):
redirect(self.settings.auth.settings.on_failed_authorization)
if not record_id and not self.has_permission('create', table, record_id):
redirect(self.settings.auth.settings.on_failed_authorization)
request = current.request
response = current.response
session = current.session
if request.extension == 'json' and request.vars.json:
request.vars.update(json_parser.loads(request.vars.json))
if next == DEFAULT:
next = request.get_vars._next \
or request.post_vars._next \
or self.settings.update_next
if onvalidation == DEFAULT:
onvalidation = self.settings.update_onvalidation
if onaccept == DEFAULT:
|
︙ | | | ︙ | |
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
|
deletable=deletable,
upload=self.settings.download_url,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
self.accepted = False
self.deleted = False
captcha = self.settings.update_captcha or \
self.settings.captcha
if record and captcha:
addrow(form, captcha.label, captcha, captcha.comment,
self.settings.formstyle,'captcha__row')
captcha = self.settings.create_captcha or \
self.settings.captcha
if not record and captcha:
addrow(form, captcha.label, captcha, captcha.comment,
self.settings.formstyle,'captcha__row')
if not request.extension in ('html','load'):
(_session, _formname) = (None, None)
else:
(_session, _formname) = \
(session, '%s/%s' % (table._tablename, form.record_id))
if formname!=DEFAULT:
_formname = formname
keepvalues = self.settings.keepvalues
if request.vars.delete_this_record:
keepvalues = False
if isinstance(onvalidation,StorageList):
onvalidation=onvalidation.get(table._tablename, [])
if form.accepts(request, _session, formname=_formname,
onvalidation=onvalidation, keepvalues=keepvalues,
hideerror=self.settings.hideerror,
detect_record_change = self.settings.detect_record_change):
self.accepted = True
response.flash = message
if log:
self.log_event(log % form.vars)
if request.vars.delete_this_record:
self.deleted = True
message = self.messages.record_deleted
callback(ondelete,form,table._tablename)
response.flash = message
callback(onaccept,form,table._tablename)
if not request.extension in ('html','load'):
raise HTTP(200, 'RECORD CREATED/UPDATED')
if isinstance(next, (list, tuple)): ### fix issue with 2.6
next = next[0]
if next: # Only redirect when explicit
if next[0] != '/' and next[:4] != 'http':
next = URL(r=request,
f=next.replace('[id]', str(form.vars.id)))
session.flash = response.flash
redirect(next)
elif not request.extension in ('html','load'):
raise HTTP(401)
return form
def create(
|
|
<
|
<
<
|
|
<
|
<
|
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
|
deletable=deletable,
upload=self.settings.download_url,
formstyle=self.settings.formstyle,
separator=self.settings.label_separator
)
self.accepted = False
self.deleted = False
captcha = self.settings.update_captcha or self.settings.captcha
if record and captcha:
addrow(form, captcha.label, captcha, captcha.comment,
self.settings.formstyle,'captcha__row')
captcha = self.settings.create_captcha or self.settings.captcha
if not record and captcha:
addrow(form, captcha.label, captcha, captcha.comment,
self.settings.formstyle,'captcha__row')
if not request.extension in ('html','load'):
(_session, _formname) = (None, None)
else:
(_session, _formname) = (session, '%s/%s' % (table._tablename, form.record_id))
if formname!=DEFAULT:
_formname = formname
keepvalues = self.settings.keepvalues
if request.vars.delete_this_record:
keepvalues = False
if isinstance(onvalidation,StorageList):
onvalidation=onvalidation.get(table._tablename, [])
if form.accepts(request, _session, formname=_formname,
onvalidation=onvalidation, keepvalues=keepvalues,
hideerror=self.settings.hideerror,
detect_record_change = self.settings.detect_record_change):
self.accepted = True
response.flash = message
if log:
self.log_event(log, form.vars)
if request.vars.delete_this_record:
self.deleted = True
message = self.messages.record_deleted
callback(ondelete,form,table._tablename)
response.flash = message
callback(onaccept,form,table._tablename)
if not request.extension in ('html','load'):
raise HTTP(200, 'RECORD CREATED/UPDATED')
if isinstance(next, (list, tuple)): ### fix issue with 2.6
next = next[0]
if next: # Only redirect when explicit
next = replace_id(next, form)
session.flash = response.flash
redirect(next)
elif not request.extension in ('html','load'):
raise HTTP(401)
return form
def create(
|
︙ | | | ︙ | |
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
|
message = self.messages.record_deleted
record = table[record_id]
if record:
callback(self.settings.delete_onvalidation,record)
del table[record_id]
callback(self.settings.delete_onaccept,record,table._tablename)
session.flash = message
if next: # Only redirect when explicit
redirect(next)
def rows(
self,
table,
query=None,
fields=None,
orderby=None,
limitby=None,
):
request = current.request
if not (isinstance(table, self.db.Table) or table in self.db.tables):
raise HTTP(404)
if not self.has_permission('select', table):
redirect(self.settings.auth.settings.on_failed_authorization)
#if record_id and not self.has_permission('select', table):
# redirect(self.settings.auth.settings.on_failed_authorization)
if not isinstance(table, self.db.Table):
|
<
|
<
|
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
|
message = self.messages.record_deleted
record = table[record_id]
if record:
callback(self.settings.delete_onvalidation,record)
del table[record_id]
callback(self.settings.delete_onaccept,record,table._tablename)
session.flash = message
redirect(next)
def rows(
self,
table,
query=None,
fields=None,
orderby=None,
limitby=None,
):
if not (isinstance(table, self.db.Table) or table in self.db.tables):
raise HTTP(404)
if not self.has_permission('select', table):
redirect(self.settings.auth.settings.on_failed_authorization)
#if record_id and not self.has_permission('select', table):
# redirect(self.settings.auth.settings.on_failed_authorization)
if not isinstance(table, self.db.Table):
|
︙ | | | ︙ | |
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
|
def select(
self,
table,
query=None,
fields=None,
orderby=None,
limitby=None,
headers={},
**attr
):
rows = self.rows(table,query,fields,orderby,limitby)
if not rows:
return None # Nicer than an empty table.
if not 'upload' in attr:
attr['upload'] = self.url('download')
if not current.request.extension in ('html','load'):
return rows.as_list()
|
|
>
|
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
|
def select(
self,
table,
query=None,
fields=None,
orderby=None,
limitby=None,
headers=None,
**attr
):
headers = headers or {}
rows = self.rows(table,query,fields,orderby,limitby)
if not rows:
return None # Nicer than an empty table.
if not 'upload' in attr:
attr['upload'] = self.url('download')
if not current.request.extension in ('html','load'):
return rows.as_list()
|
︙ | | | ︙ | |
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
|
if not refsearch:
return field.like('%'+value+'%')
else:
return lambda row: value in row[field.name][format]
except:
return None
def search(self, *tables, **args):
"""
Creates a search form and its results for a table
Example usage:
form, results = crud.search(db.test,
queries = ['equals', 'not equal', 'contains'],
query_labels={'equals':'Equals',
|
<
|
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
|
if not refsearch:
return field.like('%'+value+'%')
else:
return lambda row: value in row[field.name][format]
except:
return None
def search(self, *tables, **args):
"""
Creates a search form and its results for a table
Example usage:
form, results = crud.search(db.test,
queries = ['equals', 'not equal', 'contains'],
query_labels={'equals':'Equals',
|
︙ | | | ︙ | |
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
|
if not (isinstance(table, db.Table) or table in db.tables):
raise HTTP(404)
attributes = {}
for key in ('orderby','groupby','left','distinct','limitby','cache'):
if key in args: attributes[key]=args[key]
tbl = TABLE()
selected = []; refsearch = []; results = []
ops = args.get('queries', [])
zero = args.get('zero', '')
if not ops:
ops = ['equals', 'not equal', 'greater than',
'less than', 'starts with',
'ends with', 'contains']
ops.insert(0,zero)
|
>
>
>
>
>
>
>
|
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
|
if not (isinstance(table, db.Table) or table in db.tables):
raise HTTP(404)
attributes = {}
for key in ('orderby','groupby','left','distinct','limitby','cache'):
if key in args: attributes[key]=args[key]
tbl = TABLE()
selected = []; refsearch = []; results = []
showall = args.get('showall', False)
if showall:
selected = fields
chkall = args.get('chkall', False)
if chkall:
for f in fields:
request.vars['chk%s'%f] = 'on'
ops = args.get('queries', [])
zero = args.get('zero', '')
if not ops:
ops = ['equals', 'not equal', 'greater than',
'less than', 'starts with',
'ends with', 'contains']
ops.insert(0,zero)
|
︙ | | | ︙ | |
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
|
except: # hmmm, we should do better here
results = None
return form, results
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor()))
def fetch(url, data=None, headers={},
cookie=Cookie.SimpleCookie(),
user_agent='Mozilla/5.0'):
if data != None:
data = urllib.urlencode(data)
if user_agent: headers['User-agent'] = user_agent
headers['Cookie'] = ' '.join(['%s=%s;'%(c.key,c.value) for c in cookie.values()])
try:
from google.appengine.api import urlfetch
except ImportError:
req = urllib2.Request(url, data, headers)
html = urllib2.urlopen(req).read()
else:
method = ((data==None) and urlfetch.GET) or urlfetch.POST
while url is not None:
response = urlfetch.fetch(url=url, payload=data,
method=method, headers=headers,
allow_truncated=False,follow_redirects=False,
deadline=10)
# next request will be a get, so no need to send the data again
data = None
|
|
>
|
|
|
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
|
except: # hmmm, we should do better here
results = None
return form, results
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor()))
def fetch(url, data=None, headers=None,
cookie=Cookie.SimpleCookie(),
user_agent='Mozilla/5.0'):
headers = headers or {}
if not data is None:
data = urllib.urlencode(data)
if user_agent: headers['User-agent'] = user_agent
headers['Cookie'] = ' '.join(['%s=%s;'%(c.key,c.value) for c in cookie.values()])
try:
from google.appengine.api import urlfetch
except ImportError:
req = urllib2.Request(url, data, headers)
html = urllib2.urlopen(req).read()
else:
method = ((data is None) and urlfetch.GET) or urlfetch.POST
while url is not None:
response = urlfetch.fetch(url=url, payload=data,
method=method, headers=headers,
allow_truncated=False,follow_redirects=False,
deadline=10)
# next request will be a get, so no need to send the data again
data = None
|
︙ | | | ︙ | |
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
|
self.amfrpc3_procedures = {}
self.soap_procedures = {}
def run(self, f):
"""
example::
service = Service(globals())
@service.run
def myfunction(a, b):
return a + b
def call():
return service()
Then call it with::
wget http://..../app/default/call/run/myfunction?a=3&b=4
"""
self.run_procedures[f.__name__] = f
return f
def csv(self, f):
"""
example::
service = Service(globals())
@service.csv
def myfunction(a, b):
return a + b
def call():
return service()
Then call it with::
wget http://..../app/default/call/csv/myfunction?a=3&b=4
"""
self.run_procedures[f.__name__] = f
return f
def xml(self, f):
"""
example::
service = Service(globals())
@service.xml
def myfunction(a, b):
return a + b
def call():
return service()
Then call it with::
wget http://..../app/default/call/xml/myfunction?a=3&b=4
"""
self.run_procedures[f.__name__] = f
return f
def rss(self, f):
"""
example::
service = Service(globals())
@service.rss
def myfunction():
return dict(title=..., link=..., description=...,
created_on=..., entries=[dict(title=..., link=...,
description=..., created_on=...])
def call():
return service()
Then call it with::
wget http://..../app/default/call/rss/myfunction
"""
self.rss_procedures[f.__name__] = f
return f
def json(self, f):
"""
example::
service = Service(globals())
@service.json
def myfunction(a, b):
return [{a: b}]
def call():
return service()
Then call it with::
wget http://..../app/default/call/json/myfunction?a=hello&b=world
"""
self.json_procedures[f.__name__] = f
return f
def jsonrpc(self, f):
"""
example::
service = Service(globals())
@service.jsonrpc
def myfunction(a, b):
return a + b
def call():
return service()
Then call it with::
wget http://..../app/default/call/jsonrpc/myfunction?a=hello&b=world
"""
self.jsonrpc_procedures[f.__name__] = f
return f
def xmlrpc(self, f):
"""
example::
service = Service(globals())
@service.xmlrpc
def myfunction(a, b):
return a + b
def call():
return service()
The call it with::
wget http://..../app/default/call/xmlrpc/myfunction?a=hello&b=world
"""
self.xmlrpc_procedures[f.__name__] = f
return f
def amfrpc(self, f):
"""
example::
service = Service(globals())
@service.amfrpc
def myfunction(a, b):
return a + b
def call():
return service()
The call it with::
wget http://..../app/default/call/amfrpc/myfunction?a=hello&b=world
"""
self.amfrpc_procedures[f.__name__] = f
return f
def amfrpc3(self, domain='default'):
"""
example::
service = Service(globals())
@service.amfrpc3('domain')
def myfunction(a, b):
return a + b
def call():
return service()
The call it with::
|
|
|
|
|
|
|
|
|
|
|
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
|
self.amfrpc3_procedures = {}
self.soap_procedures = {}
def run(self, f):
"""
example::
service = Service()
@service.run
def myfunction(a, b):
return a + b
def call():
return service()
Then call it with::
wget http://..../app/default/call/run/myfunction?a=3&b=4
"""
self.run_procedures[f.__name__] = f
return f
def csv(self, f):
"""
example::
service = Service()
@service.csv
def myfunction(a, b):
return a + b
def call():
return service()
Then call it with::
wget http://..../app/default/call/csv/myfunction?a=3&b=4
"""
self.run_procedures[f.__name__] = f
return f
def xml(self, f):
"""
example::
service = Service()
@service.xml
def myfunction(a, b):
return a + b
def call():
return service()
Then call it with::
wget http://..../app/default/call/xml/myfunction?a=3&b=4
"""
self.run_procedures[f.__name__] = f
return f
def rss(self, f):
"""
example::
service = Service()
@service.rss
def myfunction():
return dict(title=..., link=..., description=...,
created_on=..., entries=[dict(title=..., link=...,
description=..., created_on=...])
def call():
return service()
Then call it with::
wget http://..../app/default/call/rss/myfunction
"""
self.rss_procedures[f.__name__] = f
return f
def json(self, f):
"""
example::
service = Service()
@service.json
def myfunction(a, b):
return [{a: b}]
def call():
return service()
Then call it with::
wget http://..../app/default/call/json/myfunction?a=hello&b=world
"""
self.json_procedures[f.__name__] = f
return f
def jsonrpc(self, f):
"""
example::
service = Service()
@service.jsonrpc
def myfunction(a, b):
return a + b
def call():
return service()
Then call it with::
wget http://..../app/default/call/jsonrpc/myfunction?a=hello&b=world
"""
self.jsonrpc_procedures[f.__name__] = f
return f
def xmlrpc(self, f):
"""
example::
service = Service()
@service.xmlrpc
def myfunction(a, b):
return a + b
def call():
return service()
The call it with::
wget http://..../app/default/call/xmlrpc/myfunction?a=hello&b=world
"""
self.xmlrpc_procedures[f.__name__] = f
return f
def amfrpc(self, f):
"""
example::
service = Service()
@service.amfrpc
def myfunction(a, b):
return a + b
def call():
return service()
The call it with::
wget http://..../app/default/call/amfrpc/myfunction?a=hello&b=world
"""
self.amfrpc_procedures[f.__name__] = f
return f
def amfrpc3(self, domain='default'):
"""
example::
service = Service()
@service.amfrpc3('domain')
def myfunction(a, b):
return a + b
def call():
return service()
The call it with::
|
︙ | | | ︙ | |
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
|
return f
return _amfrpc3
def soap(self, name=None, returns=None, args=None,doc=None):
"""
example::
service = Service(globals())
@service.soap('MyFunction',returns={'result':int},args={'a':int,'b':int,})
def myfunction(a, b):
return a + b
def call():
return service()
The call it with::
|
|
|
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
|
return f
return _amfrpc3
def soap(self, name=None, returns=None, args=None,doc=None):
"""
example::
service = Service()
@service.soap('MyFunction',returns={'result':int},args={'a':int,'b':int,})
def myfunction(a, b):
return a + b
def call():
return service()
The call it with::
|
︙ | | | ︙ | |
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
|
args = request.args
def none_exception(value):
if isinstance(value, unicode):
return value.encode('utf8')
if hasattr(value, 'isoformat'):
return value.isoformat()[:19].replace('T', ' ')
if value == None:
return '<NULL>'
return value
if args and args[0] in self.run_procedures:
r = universal_caller(self.run_procedures[args[0]],
*args[1:], **dict(request.vars))
s = cStringIO.StringIO()
if hasattr(r, 'export_to_csv_file'):
|
|
|
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
|
args = request.args
def none_exception(value):
if isinstance(value, unicode):
return value.encode('utf8')
if hasattr(value, 'isoformat'):
return value.isoformat()[:19].replace('T', ' ')
if value is None:
return '<NULL>'
return value
if args and args[0] in self.run_procedures:
r = universal_caller(self.run_procedures[args[0]],
*args[1:], **dict(request.vars))
s = cStringIO.StringIO()
if hasattr(r, 'export_to_csv_file'):
|
︙ | | | ︙ | |
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
|
self.error()
response.headers['Content-Type'] = 'application/rss+xml'
return serializers.rss(feed)
def serve_json(self, args=None):
request = current.request
response = current.response
response.headers['Content-Type'] = 'text/x-json'
if not args:
args = request.args
d = dict(request.vars)
if args and args[0] in self.json_procedures:
s = universal_caller(self.json_procedures[args[0]],*args[1:],**d)
if hasattr(s, 'as_list'):
s = s.as_list()
return response.json(s)
self.error()
class JsonRpcException(Exception):
def __init__(self,code,info):
self.code,self.info = code,info
def serve_jsonrpc(self):
import contrib.simplejson as simplejson
def return_response(id, result):
return serializers.json({'version': '1.1',
'id': id, 'result': result, 'error': None})
def return_error(id, code, message):
return serializers.json({'id': id,
'version': '1.1',
'error': {'name': 'JSONRPCError',
'code': code, 'message': message}
})
request = current.request
methods = self.jsonrpc_procedures
data = simplejson.loads(request.body.read())
id, method, params = data['id'], data['method'], data.get('params','')
if not method in methods:
return return_error(id, 100, 'method "%s" does not exist' % method)
try:
s = methods[method](*params)
if hasattr(s, 'as_list'):
s = s.as_list()
|
|
<
<
>
>
|
|
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
|
self.error()
response.headers['Content-Type'] = 'application/rss+xml'
return serializers.rss(feed)
def serve_json(self, args=None):
request = current.request
response = current.response
response.headers['Content-Type'] = 'application/json; charset=utf-8'
if not args:
args = request.args
d = dict(request.vars)
if args and args[0] in self.json_procedures:
s = universal_caller(self.json_procedures[args[0]],*args[1:],**d)
if hasattr(s, 'as_list'):
s = s.as_list()
return response.json(s)
self.error()
class JsonRpcException(Exception):
def __init__(self,code,info):
self.code,self.info = code,info
def serve_jsonrpc(self):
def return_response(id, result):
return serializers.json({'version': '1.1',
'id': id, 'result': result, 'error': None})
def return_error(id, code, message):
return serializers.json({'id': id,
'version': '1.1',
'error': {'name': 'JSONRPCError',
'code': code, 'message': message}
})
request = current.request
response = current.response
response.headers['Content-Type'] = 'application/json; charset=utf-8'
methods = self.jsonrpc_procedures
data = json_parser.loads(request.body.read())
id, method, params = data['id'], data['method'], data.get('params','')
if not method in methods:
return return_error(id, 100, 'method "%s" does not exist' % method)
try:
s = methods[method](*params)
if hasattr(s, 'as_list'):
s = s.as_list()
|
︙ | | | ︙ | |
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
|
for method, doc in dispatcher.list_methods()]),
]
return {'body': body}
def __call__(self):
"""
register services with:
service = Service(globals())
@service.run
@service.rss
@service.json
@service.jsonrpc
@service.xmlrpc
@service.jsonrpc
@service.amfrpc
@service.amfrpc3('domain')
@service.soap('Method', returns={'Result':int}, args={'a':int,'b':int,})
expose services with
def call(): return service()
|
|
<
|
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
|
for method, doc in dispatcher.list_methods()]),
]
return {'body': body}
def __call__(self):
"""
register services with:
service = Service()
@service.run
@service.rss
@service.json
@service.jsonrpc
@service.xmlrpc
@service.amfrpc
@service.amfrpc3('domain')
@service.soap('Method', returns={'Result':int}, args={'a':int,'b':int,})
expose services with
def call(): return service()
|
︙ | | | ︙ | |
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
|
finally:
lock.release()
def __init__(self,plugin=None,**defaults):
if not plugin:
self.__dict__.clear()
settings = self.__getattr__(plugin)
settings.installed = True
[settings.update({key:value}) for key,value in defaults.items() if not key in settings]
def __getattr__(self, key):
if not key in self.__dict__:
self.__dict__[key] = Storage()
return self.__dict__[key]
def keys(self):
return self.__dict__.keys()
def __contains__(self,key):
return key in self.__dict__
if __name__ == '__main__':
import doctest
doctest.testmod()
|
|
>
<
|
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
|
finally:
lock.release()
def __init__(self,plugin=None,**defaults):
if not plugin:
self.__dict__.clear()
settings = self.__getattr__(plugin)
settings.installed = True
[settings.update({key:value}) for key,value in defaults.items() \
if not key in settings]
def __getattr__(self, key):
if not key in self.__dict__:
self.__dict__[key] = Storage()
return self.__dict__[key]
def keys(self):
return self.__dict__.keys()
def __contains__(self,key):
return key in self.__dict__
if __name__ == '__main__':
import doctest
doctest.testmod()
|