def checkout(): rand_id = str(uuid1()) epoch = round(epochtime()) # round() removes the decimals amount = '100.00' # Step 1: JWT Creation # > jwt.io website payload = { 'jti': rand_id, 'iat': epoch, 'iss': iss, 'OrgUnitId': OrgUnitId, 'Payload': { 'OrderDetails': { 'OrderNumber': 'Order: ' + rand_id[10:], 'Amount': amount.replace('.', ''), # 100.00 to 10000 'CurrencyCode': '840', } }, 'ObjectifyPayload': True, } jwt_ = jwt.encode(payload, apiKey) context = { 'jwt': jwt_.decode('utf-8') # decodes from bytes to string } # > Pass to frontend return render_template('checkout.html', context=context)
def checkout(): session['rand_id'] = str(uuid1()) session['amount'] = '150.01' session['currency'] = '840' # USD epoch = round(epochtime()) # round() removes the decimals # Step 1: JWT Creation # > jwt.io website payload = { 'OrgUnitId': OrgUnitId, 'iss': iss, 'iat': epoch, 'exp': epoch + 1000, 'jti': session['rand_id'], 'Payload': { 'OrderDetails': { 'OrderNumber': session['rand_id'], 'Amount': session['amount'].replace('.', ''), # 100.00 to 10000 'CurrencyCode': session['currency'], } }, 'ObjectifyPayload': True, } jwt_ = jwt.encode(payload, apiKey) context = { 'jwt': jwt_.decode('utf-8'), } return render_template('checkout.html', context=context)
def OnHover(self, x, y, dragResult): if not hasattr(self, 'lastHover'): self.lastHover = epochtime() - 1 if epochtime() > self.lastHover + .05: # 20 scrolls a second self.lastHover = epochtime() self.RefreshCanvasItems(resort=False) unscrolledPosition = wx.Point(*self.CalcUnscrolledPosition(x, y)) dragResult = wx.DragMove if self.dragState is not None: if self.IsValidDragPosition(unscrolledPosition): self.dragState.HandleDrag(unscrolledPosition) else: # save unscrolledPosition in case an email is dragged in self.fileDragPosition = unscrolledPosition return dragResult
def OnHover (self, x, y, dragResult): if not hasattr(self, 'lastHover'): self.lastHover = epochtime() - 1 if epochtime() > self.lastHover + .05: # 20 scrolls a second self.lastHover = epochtime() self.RefreshCanvasItems(resort=False) unscrolledPosition = wx.Point(*self.CalcUnscrolledPosition(x, y)) dragResult = wx.DragMove if self.dragState is not None: if self.IsValidDragPosition(unscrolledPosition): self.dragState.HandleDrag(unscrolledPosition) else: # save unscrolledPosition in case an email is dragged in self.fileDragPosition = unscrolledPosition return dragResult
def checkout(): if have_rand_id[0] == False: global rand_id rand_id = str(uuid1()) # string of universally unique ID have_rand_id[0] = True if request.method == 'GET': epoch = round(epochtime()) # round() removes the decimal amount = '100.00' # arbitrary amount that changes depending on the cart # Step 1: JWT Creation # > jwt.io website payload = { 'jti': rand_id, 'iat': epoch, 'iss': iss, 'OrgUnitId': OrgUnitId, 'Payload': { 'OrderDetails': { 'OrderNumber': 'Order: ' + rand_id[10:], 'Amount': amount.replace('.', ''), # 100.00 to 10000 'CurrencyCode': '840', } }, 'ObjectifyPayload': True, } jwt_ = jwt.encode(payload, apiKey) # creates the JWT context = { 'jwt': jwt_.decode('utf-8'), # decodes from bytes to string # needed for Songbird initialze 'amount': amount, # needed for JS order object 'orderNumber': 'Order: ' + rand_id[10:] # needed for JS order object } # > Pass to frontend return render_template('checkout.html', context=context) elif request.method == 'POST': # Step 10: JWT Validation returned_jwt = request.get_data().decode('utf-8') try: validate_jwt = jwt.decode(returned_jwt, apiKey, audience=rand_id) print(validate_jwt) return 'Successful JWT validation' # proceed with payment except: return 'JWT Tampering!' # stop payment
def encode_mail(sender, receiver, data): "data must be validated by check_mail" from kryptomime.mail import create_mail, create_mime, check_charset, protect_mail from time import time as epochtime import email.utils from email.mime.text import MIMEText from six import iteritems from idapi.models import Message subject = data['subject'] time = data.get('date') if not time: time = epochtime() parts = data.get('parts',None) if parts: # multi-part mail = None for i,part in enumerate(parts): ctype = part.get('content-type','text/plain').lower().split('/') encoding = part.get('content-encoding') content = part['content'] content, charset = check_charset(content,part.get('content-charset')) if not i: msg = create_mail(sender,receiver,subject,content,time=time,subtype=ctype[1], charset=charset,encoding=encoding,attach=[]) else: msg = create_mime(content,*ctype,charset=charset,encoding=encoding) filename= part.get('filename') filename = dict(filename=filename) if filename else {} msg.add_header('Content-Disposition', 'attachment', **filename) params = part.get('content-params',{}) if params: for k,v in iteritems(params): msg.set_param(k,v) if i: mail.attach(msg) else: mail = msg else: # single part ctype = data.get('content-type','text/plain').lower().split('/') encoding = data.get('content-encoding') body, charset = check_charset(data['content'],data.get('content-charset')) mail = create_mail(sender,receiver,subject,body,time=time,subtype=ctype[1], charset=charset,encoding=encoding) params = data.get('content-params',{}) if params: for k,v in iteritems(params): mail.set_param(k,v) return protect_mail(mail)
def time(): current_time = str(asctime(gmtime(epochtime()))) return current_time
def time(): time = str(asctime(gmtime(epochtime()))) return time
def create_mail(input, app, user): from time import time as epochtime from ekklesia.mail import Template from idapi.models import Message ids = getattr(settings, 'EMAIL_IDS', {}) templates = getattr(settings, 'EMAIL_TEMPLATES', {}) clients = getattr(settings, 'EMAIL_CLIENTS', {}) try: allowed = clients[app.client_id] identity = input['identity'] opts = ids[identity] recv, send, attach = allowed[identity] assert send != False except: return None template = input.get('template', None) if send is None and 'templates' in opts: if not template in opts['templates']: return None if template: subject, body = templates[template] if type(subject) == str: subject = Template(subject) if type(body) == str: body = Template(body) else: subject, body = Template(u'{subject}'), Template(u'{body}') sign, encrypt = input.get('sign', False), input.get('encrypt', False) if sign and not 'key' in opts: return None if encrypt and not user.publickeys.filter(active=True).exists(): return None content = input.get('content', {}) if not content: return None data = { 'subject': subject(**content), 'encrypt': encrypt, 'sign': sign, 'date': epochtime() } main = {'content': body(**content)} for field in ('content-type', 'content-params', 'content-charset', 'content-encoding'): if not field in input: continue if field == 'content-params' and type(input[field]) != dict: return None main[field] = input[field] if 'parts' in input: parts = [main] attachments = input.get('parts', []) if not type(attachments) == dict: return None for a in attachments: part = {} if type(a) == str: part['content'] = a elif type(a) == dict: # dict if not 'content' in a: return None part['content'] = a['content'] for field in ('content-type', 'content-params', 'content-charset', 'content-encoding', 'filename'): if not field in a: continue if field == 'content-params' and type(a[field]) != dict: return None part[field] = a[field] else: return None attachments.append(p) data['parts'] = attachments else: data.update(main) data['status'] = 'queued' # whether to keep sent msg (explicit delete) or auto-delete after send data['keep'] = input.get('keep', True) #print data msg = Message(user=user, application=app, identity=identity, email=True, outgoing=True, crypto=(sign or encrypt), data=data) #print msg.__dict__, user.email msg.save() # FIXME: notify encrypt/send return msg
def encode_mail(msg, sender): from kryptomime.mail import create_mail, create_mime, check_charset from time import time as epochtime import email.utils from email.mime.text import MIMEText from six import iteritems from idapi.models import Message user, data = msg.user, msg.data receiver = user.email subject = data['subject'] time = data.get('date', epochtime()) parts = data.get('parts', None) if parts: # multi-part mail = None for i, part in enumerate(parts): ctype = part.get('content-type', 'text/plain').lower().split('/') encoding = part.get('content-encoding') content = part['content'] content, charset = check_charset(content, part.get('content-charset')) if i: msg = create_mime(content, *ctype, charset=charset, encoding=encoding) filename = part.get('filename') filename = dict(filename=filename) if filename else {} msg.add_header('Content-Disposition', 'attachment', **filename) else: assert ctype[0] == 'text' msg = create_mail(sender, receiver, subject, content, time=time, subtype=ctype[1], charset=charset, encoding=encoding) params = part.get('content-params', {}) if params: assert type(params) == dict for k, v in iteritems(params): msg.set_param(k, v) if i: mail.attach(msg) else: mail = msg else: # single part ctype = data.get('content-type', 'text/plain').lower().split('/') assert ctype[0] == 'text' encoding = data.get('content-encoding') body, charset = check_charset(data['content'], data.get('content-charset')) mail = create_mail(sender, receiver, subject, body, time=time, subtype=ctype[1], charset=charset, encoding=encoding) params = data.get('content-params', {}) if params: assert type(params) == dict for k, v in iteritems(params): mail.set_param(k, v) #print mail return mail
def check_mail(input,user,app): from time import time as epochtime from ekklesia.mail import Template from idapi.models import Message from rest_framework.exceptions import ValidationError, PermissionDenied, MethodNotAllowed ids = settings.EMAIL_IDS templates = settings.EMAIL_TEMPLATES if app: clients = settings.EMAIL_CLIENTS try: permissions = clients[app.client_id] except KeyError: raise PermissionDenied(dict(error='client_not_permitted', details='client does not have permission to use the email interface')) if not 'identity' in input: raise ValidationError(dict(error='identity_missing', details='the identity is not specified')) identity = input['identity'] if not identity in ids: raise ValidationError(dict(error='identity_unknown', details='the identity is unknown')) opts = ids[identity] if app: if not identity in permissions: raise ValidationError(dict(error='identity_not_permitted', details='the identity is not permitted for this client')) recv, send, attach = permissions[identity] if send is False: raise MethodNotAllowed('post') else: recv = send = attach = True template = input.get('template',None) if template: if send is None and 'templates' in opts: if not template in opts['templates']: raise ValidationError(dict(error='template_not_permitted', details='the template is not permitted for this identity')) if not template in templates: raise ValidationError(dict(error='template_unknown', details='template is unknown')) subject,body = templates[template] if type(subject)==str: subject = Template(subject) if type(body)==str: body = Template(body) else: subject, body = Template(u'{subject}'), Template(u'{body}') sign, encrypt = input.get('sign',False),input.get('encrypt',False) if sign and not 'key' in opts: raise ValidationError(dict(error='signing', details='signing not supported for this identity')) if encrypt and not user.publickeys.filter(active=True).exists(): raise ValidationError(dict(error='pubkey_missing', details='the public key for this user is missing')) def check_content(data,out,extra=(),force_text=False): content = data.get('content') if not content: raise ValidationError(dict(error='content_missing', details='message content is missing')) for field in ('content-type','content-params','content-charset','content-encoding')+extra: if not field in data: continue if field=='content-params' and type(data[field])!=dict: raise ValidationError(dict(error='type_error', details='content params must be a dict')) elif field=='content-type': ctype = data[field].split('/') if not len(ctype)==2 or not (ctype[0] and ctype[1]): raise ValidationError(dict(error='type_error', details="invalid content type")) if force_text and not ctype[0]: raise ValidationError(dict(error='type_error', details="content-type text expected")) out[field] = data[field] return content main = {} content = check_content(input,main,force_text=True) data = dict(subject=subject(**content),encrypt=encrypt,sign=sign,date=epochtime()) main['content'] = body(**content) def check_encoding(data): from kryptomime.mail import check_charset charset = data.get('content-charset') encoding = data.get('content-encoding') if not charset and not encoding: return if encoding=='7bit': if not charset: charset = 'us-ascii' elif not charset in ('ascii','us-ascii'): raise ValidationError(dict(error='type_error', details="encoding and charset mismatch")) try: check_charset(data['content'], charset) except UnicodeError: raise ValidationError(dict(error='type_error', details="charset does not match data")) check_encoding(main) if 'parts' in input: if not attach: raise ValidationError(dict(error='attachment_not_permitted', details='attachments are not permitted for this client')) parts = [main] attachments = input.get('parts',[]) if not isinstance(attachments,(list,tuple)): raise ValidationError(dict(error='type_error', details='parts must be a list')) for a in attachments: part = {} if type(a)==str: part['content'] = a elif type(a)==dict: # dict part['content'] = check_content(a,part,extra=('filename',)) check_encoding(part) else: raise ValidationError(dict(error='type_error', details='part must be a string or dict')) parts.append(part) data['parts'] = parts else: data.update(main) # whether to keep sent msg (explicit delete) or auto-delete after send data['acknowledge'] = input.get('acknowledge',False) return data, identity, sign or encrypt