Esempio n. 1
0
 def setUp(self):
     signer = Signer()
     signed_email = signer.sign('*****@*****.**')
     self.client.cookies = SimpleCookie({'_ofs': signed_email})
Esempio n. 2
0
 def get_basket_hash(self, basket_id):
     return Signer().sign(basket_id)
Esempio n. 3
0
def unsign_string(signed_string: str, salt: str) -> str:
    signer = Signer(salt=salt)
    return signer.unsign(signed_string)
Esempio n. 4
0
 def unsign_username(token):
     return Signer(salt=SET_PASSWORD_SALT).unsign(token)
Esempio n. 5
0
def sign_obj_id(obj_id, salt=None):
    signer = Signer(salt=salt)
    value = signer.sign("%s@%s" % (obj_id, settings.TWILIO_ACCOUNT_SID))
    return value
Esempio n. 6
0
def get_published_properties(user, store, meta):
    signer = Signer()

    data = {
        'logged_in':
        True,
        'uid':
        user.pk,
        'username':
        user.username,
        'name': (user.first_name if user.first_name else user.username),
        'email':
        user.email,
        'configured':
        store.configured,
        'taskd_credentials':
        store.taskrc.get('taskd.credentials'),
        'taskd_server':
        store.taskrc.get('taskd.server'),
        'taskd_server_is_default':
        store.sync_uses_default_server,
        'streaming_enabled': (settings.STREAMING_UPDATES_ENABLED
                              and store.sync_uses_default_server),
        'streaming_key':
        signer.sign(str(store.pk)),
        'taskd_files':
        store.taskd_certificate_status,
        'twilio_auth_token':
        store.twilio_auth_token,
        'sms_whitelist':
        store.sms_whitelist,
        'sms_arguments':
        store.sms_arguments,
        'sms_replies':
        store.sms_replies,
        'email_whitelist':
        store.email_whitelist,
        'task_creation_email_address':
        '*****@*****.**' % (store.secret_id),
        'taskrc_extras':
        store.taskrc_extras,
        'api_key':
        store.api_key.key,
        'tos_up_to_date':
        meta.tos_up_to_date,
        'privacy_policy_up_to_date':
        meta.privacy_policy_up_to_date,
        'feed_url':
        reverse('feed', kwargs={
            'uuid': store.secret_id,
        }),
        'ical_waiting_url':
        reverse('ical_feed',
                kwargs={
                    'variant': 'waiting',
                    'secret_id': store.secret_id,
                }),
        'ical_due_url':
        reverse('ical_feed',
                kwargs={
                    'variant': 'due',
                    'secret_id': store.secret_id,
                }),
        'sms_url':
        reverse('incoming_sms', kwargs={
            'username': user.username,
        }),
        'colorscheme':
        meta.colorscheme,
        'repository_head':
        store.repository.head(),
        'sync_enabled':
        store.sync_enabled,
        'pebble_cards_enabled':
        store.pebble_cards_enabled,
        'feed_enabled':
        store.feed_enabled,
        'ical_enabled':
        store.ical_enabled,
        'auto_deduplicate':
        store.auto_deduplicate,
        'trello_board_url':
        (store.trello_board.meta['url'] if store.trello_board else None),
        'system_udas':
        get_system_udas_as_config(),
    }

    try:
        data.update({
            'udas': [{
                'field': k,
                'label': v.label,
                'type': v.__class__.__name__
            } for k, v in store.client.config.get_udas().items()],
        })
    except exceptions.InvalidTaskwarriorConfiguration:
        pass

    return data
Esempio n. 7
0
 def verification_hash(self):
     signer = Signer(salt='oscar.apps.order.Order')
     return signer.sign(self.number)
Esempio n. 8
0
 def encryptId(pedido_id):
     signer = Signer()
     return signer.sign(pedido_id)
Esempio n. 9
0
 def decryptId(encrypted_id):
     try:
         signer = Signer()
         return int(signer.unsign(encrypted_id))
     except BadSignature:
         return None
Esempio n. 10
0
def register_auth(request):
    if request.method != 'POST':
        return redirect('/register')

    #see if all were provided
    if (not (request.POST.get('name') and request.POST.get('email') and
             request.POST.get('password') and request.POST.get('confirm'))):

        #TODO error handling, give them error messages
        return redirect('/register')

    input_email = request.POST['email']
    input_name = request.POST['name']
    input_password = request.POST['password']
    input_confirm = request.POST['confirm']

    #see if email is an email, password is right TODO
    regex_email = r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)'

    #use regex. See if paswords match. see is password is long enough, enough special chars, etc

    #see if email already exists

    preExistingUsers = Calendo_User.objects.raw(
        'SELECT * FROM webapp_calendo_user WHERE "Email"=%s', [input_email])

    print(len(list(preExistingUsers)))

    if (len(list(preExistingUsers)) > 0):
        #TODO preexisting user error message
        print("omg kill me")
        return redirect('/register')

    #salt, hash password TODO
    signer = Signer()
    password_hashed = input_password
    password_hashed = signer.sign(input_password)
    password_hashed = password_hashed[password_hashed.find(":") + 1:]

    #insert into database
    insertNewUserResult = Calendo_User(Name=input_name,
                                       Email=input_email,
                                       Password=password_hashed)
    insertNewUserResult.save()

    #genereate confirm email code

    codeGenerated = confirm_code_generator()
    insertNewEmailConfirmCodeResult = Confirm_Email(
        UserId=insertNewUserResult.id,
        Email=input_email,
        Code=codeGenerated,
        IsConfirmed=False)
    insertNewEmailConfirmCodeResult.save()

    #send email to given email TODO

    send_mail(
        'Verify your Calendo Account, ' + input_name,
        """
		Hello """ + input_name + """! \n\n 
		
		To verify your Calendo account, please click on the link below:\n

		www.calen-do.com/confirm_email?code=""" + codeGenerated + """\n\n

		Have a nice day!\n
		-Calendo Team
		""",
        '*****@*****.**',
        [input_email],
        fail_silently=False,
    )

    #render response
    return render(request, 'webapp/register-complete.html',
                  {'email': input_email})
Esempio n. 11
0
def login_auth(request):
    print("X IN LOGIN AUTH")
    if (request.method != 'POST'):
        return redirect('/login')

    if (not (request.POST.get('email') and request.POST.get('password'))):
        #TODO error handling, give them error messages
        return redirect('/login')

    print("X IN LOGIN AUTH2")
    input_email = request.POST['email']
    input_password = request.POST['password']

    #see if provided credentials are legal TODO, length pass, is an eail, etc

    #query database for given email
    userResult = Calendo_User.objects.raw(
        'SELECT * FROM webapp_calendo_user  WHERE "Email"=%s',
        [request.POST['email']])

    print("X IN LOGIN AUTH3")
    #if not exactly 1 row, error
    if (len(list(userResult)) != 1):
        print("oh shits")
        return redirect('/login?auth_failed=true&noUser=true')

    userOfInterest = userResult[0]

    print("X IN LOGIN AUTH4")
    #Hash given password. Check with database. error back if not right
    signer = Signer()

    input_password_enc = signer.sign(input_password)
    input_password_enc = input_password_enc[input_password_enc.find(":") + 1:]

    print("X IN LOGIN AUTH41")
    if (input_password_enc == userOfInterest.Password):

        print("X IN LOGIN AUTH42")
        #If still hasnt confrmed password, error it
        if (not (userOfInterest.isConfirmed)):
            #TODO let user know they have to confirm their email
            return render(request, 'webapp/home.html',
                          {'userResult': userResult[0]})

        #create token in database TODO

        print("X IN LOGIN AUTH5")
        session_token = login_token_generator()
        token_death_date = int(time.time()) + 60 * 2

        insertSessionTokenResult = Session(SessionId=session_token,
                                           UserId=userOfInterest.id,
                                           UserEmail=userOfInterest.Email,
                                           DeathDate=token_death_date)
        insertSessionTokenResult.save()

        print("X IN LOGIN AUTH6")
        t = loader.get_template('webapp/home_redirect.html')
        c = {'userResult': userResult[0]}

        response = HttpResponse(t.render(c, request))
        response.set_cookie('calendo_session_token', session_token)

        print("Cook that was set:")
        print("Cook that was set:")
        print("Cook that was set:")
        print("Cook that was set:")
        print("Cook that was set:")
        print("Cook that was set:")
        print(session_token)
        print("OH YES BABY")
        return response

    else:
        print("OH NOOOOOOOOO")
        return redirect('./home.html')
Esempio n. 12
0
def verify_zeus_url_signature(submission_id, signature):
    signer = Signer(salt=ZEUS_URL_SALT)
    try:
        return signer.unsign(signature) == submission_id
    except BadSignature:
        return False
Esempio n. 13
0
def zeus_url_signature(submission_id):
    signer = Signer(salt=ZEUS_URL_SALT)
    return signer.sign(submission_id)
Esempio n. 14
0
def chat_path(channel, participant_id):
    channel_and_id = '{}/{}'.format(channel, participant_id)
    channel_and_id_signed = Signer(sep='/').sign(channel_and_id)

    return '/otreechat_core/{}/'.format(channel_and_id_signed)
Esempio n. 15
0
def get_signature(secret, body, timestamp, url):
    if not body:
        body = ""

    signer = Signer(key=secret)
    return signer.signature( ":".join([body, timestamp, url]) )
Esempio n. 16
0
def get_signed_purpose(purpose):
    signer = Signer()
    return signer.sign(SALT + purpose)
Esempio n. 17
0
 def __init__(self, data):
     if self.use_timestamp and self.timestamp_field not in data:
         data = data.copy()
         data[self.timestamp_field] = get_current_timestamp()
     self._data = data
     self._signer = Signer(self.salt)
Esempio n. 18
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     # code and SECRET_KEY will be needed to validate
     self._signer = Signer(salt=self.code)
Esempio n. 19
0
 def get_anonymous_edit_url(self):
     signer = Signer()
     signature = signer.sign(self.pk)
     return reverse('map_anonymous_edit_url',
                    kwargs={'signature': signature})
Esempio n. 20
0
 def resolve_storage_key(self, info, **kwargs):
     signer = Signer()
     #TODO do the right thing
     payload = ''.join([self.username, self.password])
     return signer.sign(payload)
Esempio n. 21
0
import random
import time

from datadog import statsd
from django.core.signing import Signer

from cabinet import cabinet_api
from core.utils.constants import HWCentralQuestionType

SIGNER = Signer()

def deal(undealt_questions):
    """
    This method takes undealt questions, deals them (variable value selection, substitution and evaluation) and then
    returns just the dealt questions as regular data models
    """
    dealt_questions = []
    for undealt_question in undealt_questions:
        dealt_questions.append(undealt_question.deal())
    return dealt_questions

def shuffle(undealt_questions):
    """
    Shuffles the given list of questions as well as the options of any MCQs in the list using the given technique
    """
    # first shuffle question order (IN PLACE)
    random.shuffle(undealt_questions)

    for undealt_question in undealt_questions:
        for subpart in undealt_question.question_data.subparts:
            # check if the subpart has options whose order can be shuffled
Esempio n. 22
0
    def build_webhook_token() -> typing.Tuple[str, typing.Any]:
        unsigned = str(uuid.uuid4())

        return unsigned, Signer().sign_object(unsigned)
Esempio n. 23
0
 def signed_username(self):
     return Signer(salt=SET_PASSWORD_SALT).sign(self.username)
Esempio n. 24
0
def sign_string(string: str) -> Tuple[str, str]:
    salt = secrets.token_hex(32)
    signer = Signer(salt=salt)
    return signer.sign(string), salt
Esempio n. 25
0
    def execute(self):
        from django.core import management
        from ...models import WIncident, WIncident_write, WIncidentAnimals, Animal, Mouse, WIncidentcomment, WIncidentPups, Pup, WIncidentanimals_write, WIncidentpups_write
        from ...models import SacrificeIncidentToken
        from django.core.mail import EmailMultiAlternatives, send_mail
        from datetime import datetime, timedelta
        from django.conf import settings
        from django.core.signing import Signer
        from django.core.mail import EmailMultiAlternatives, send_mail
        from django.template.loader import render_to_string
        from django.core.mail import EmailMessage
        from django.conf import settings
        import logging
        import sys

        mousedb = 'mousedb_test'
        mousedb_write = 'mousedb_test_write'
        LINES_PROHIBIT_SACRIFICE = getattr(settings, "LINES_PROHIBIT_SACRIFICE", None)
        logger = logging.getLogger('myscriptlogger')
        TIMEDIFF = getattr(settings, "TIMEDIFF", 2)
        try:
            today = datetime.now().date()
            incidentlist = WIncident.objects.using(mousedb).all().filter(incidentclass=22).filter(status=5)
            for incident in incidentlist:
                skip = 0
                error = 0
                i = 0
                animallist = WIncidentAnimals.objects.using(mousedb).filter(incidentid = incident.incidentid)
                puplist = WIncidentPups.objects.using(mousedb).filter(incidentid = incident.incidentid)
                count_mice = animallist.count()
                count_pups = puplist.count()
                count_animals = count_mice + count_pups
                #logger.debug('{}: count_animals {}'.format(datetime.now(), count_animals))
                for pyratmouse in animallist:
                    i = i + 1
                    try:
                        animouseFilter = Animal.objects.filter(mouse_id=pyratmouse.animalid)
                        if len(animouseFilter) == 0: # Check if pup has been weaned
                            if Mouse.objects.using(mousedb).filter(id = pyratmouse.animalid).exists():
                                v_mouse = Mouse.objects.using(mousedb).get(id = pyratmouse.animalid)
                            else:
                                continue
                            if Animal.objects.filter(database_id=v_mouse.eartag).exists():
                                animouse = Animal.objects.get(database_id=v_mouse.eartag)
                                animouse.mouse_id = v_mouse.id
                                animouse.animal_type = "mouse"
                                animouse.save() # Save new animal_id (id changed because pup is now an adult)
                                skip = 1 # with the next run the script will find the pup with the new mouse_id
                            else:
                                continue
                        else:
                            animouse = Animal.objects.get(mouse_id=pyratmouse.animalid)
                        if (animouse.new_owner):
                            continue
                        if (animouse.available_to >= today):
                            skip = 1
                            break
                    except BaseException as e: 
                            error = 1
                            skip = 1
                            ADMIN_EMAIL = getattr(settings, "ADMIN_EMAIL", None)
                            send_mail("AniShare Check Status Error", 'Fehler {} bei der Statusüberprüfung des Auftrags {} (Maus) in Zeile {}'.format( e, incident.incidentid, sys.exc_info()[2].tb_lineno), ADMIN_EMAIL, [ADMIN_EMAIL])
                for pyratpup in puplist:
                    i = i + 1
                    try:
                        anipupFilter = Animal.objects.filter(pup_id=pyratpup.pupid)
                        if len(anipupFilter) == 0:
                            continue
                        anipup = Animal.objects.get(pup_id=pyratpup.pupid)
                        if (anipup.new_owner):
                            continue
                        if (anipup.available_to >= today):
                            skip = 1
                            break
                    except BaseException as e:  
                            error = 1
                            skip = 1
                            ADMIN_EMAIL = getattr(settings, "ADMIN_EMAIL", None)
                            send_mail("AniShare Check Status Error", 'Fehler {} bei der Statusüberprüfung des Auftrags {} (Pup) in Zeile {}'.format( e, incident.incidentid,sys.exc_info()[2].tb_lineno), ADMIN_EMAIL, [ADMIN_EMAIL])
                if (skip == 0 and i == count_animals):
                    incident_write = WIncident_write.objects.using(mousedb_write).get(incidentid=incident.incidentid)
                    incident_write.status = 1
                    incident_write.closedate = datetime.now()
                    incident_write.save(using=mousedb_write)
                    logger.debug('{}: Incident status {} has been changed to 1.'.format(datetime.now(), incident.incidentid))
                    new_comment = WIncidentcomment()
                    new_comment.incidentid = incident
                    new_comment.comment = 'AniShare: Request status changed to closed'
                    new_comment.save(using=mousedb_write) 
                    new_comment.commentdate = new_comment.commentdate + timedelta(hours=TIMEDIFF)
                    new_comment.save(using=mousedb_write)
                    if incident.sacrifice_reason:

                        # save token and send to Add to AniShare initiator to create sacrifice request
                        new_sacrifice_incident_token            = SacrificeIncidentToken()
                        new_sacrifice_incident_token.initiator  = incident.initiator.username
                        new_sacrifice_incident_token.incidentid = incident.incidentid
                        signer = Signer()
                        new_sacrifice_incident_token.urltoken   = signer.sign("{}".format(incident.incidentid))
                        new_sacrifice_incident_token.save()
                        
                        # Send email to initiator to confirm sacrifice request
                        animallist = Animal.objects.filter(pyrat_incidentid = incident.incidentid)
                        i = 0
                        for animal in animallist:
                            if animal.new_owner:
                                animallist = animallist.exclude(pk=animal.pk)
                            if animal.line in LINES_PROHIBIT_SACRIFICE:
                                animallist = animallist.exclude(pk=animal.pk) 
                            i = i + 1
                        if len(animallist) > 0:
                            initiator_name = "{} {}".format(incident.initiator.firstname,incident.initiator.lastname)
                            sacrifice_link = "{}/{}/{}".format(settings.DOMAIN,"confirmsacrificerequest",new_sacrifice_incident_token.urltoken)
                            message = render_to_string('email_animals_sacrifice.html',{'animals':animallist, 'initiator':initiator_name, 'sacrifice_link':sacrifice_link})
                            subject = "Confirmation sacrifice request"
                            recipient = incident.initiator.email
                            msg = EmailMessage(subject, message, "*****@*****.**", [recipient])
                            msg.content_subtype = "html"
                            msg.send()
                            logger.debug('Mail Confirmation sacrifice request an {} mit Link {} gesendet'.format(recipient,sacrifice_link))
                 
        except BaseException as e:  
            logger.error('{}: AniShare Importscriptfehler hourly_check_status_incidents.py: Fehler {} in Zeile {}'.format(datetime.now(),e, sys.exc_info()[2].tb_lineno)) 
            ADMIN_EMAIL = getattr(settings, "ADMIN_EMAIL", None)
            send_mail("AniShare Importscriptfehler hourly_check_status_incidents.py", 'Fehler {} in Zeile {}'.format(e,sys.exc_info()[2].tb_lineno), ADMIN_EMAIL, [ADMIN_EMAIL])
        management.call_command("clearsessions")
Esempio n. 26
0
 def make_account_token(cls, email):
     signer = Signer()
     value = signer.sign(email)
     return value
Esempio n. 27
0
def sign_string(string: str) -> Tuple[str, str]:
    salt = generate_random_token(64)
    signer = Signer(salt=salt)
    return signer.sign(string), salt
Esempio n. 28
0
def get_qr_url_protection_signed_token(qr_code_options: QRCodeOptions):
    """Generate a signed token to handle view protection."""
    url_protection_options = get_url_protection_options()
    signer = Signer(key=url_protection_options[constants.SIGNING_KEY], salt=url_protection_options[constants.SIGNING_SALT])
    token = signer.sign(get_qr_url_protection_token(qr_code_options, _RANDOM_TOKEN))
    return token
Esempio n. 29
0
        print(error)
    return slugify(text)


def available_birth_years(min_year=1900):
    return [
        f'{year}' for year in range(min_year,
                                    datetime.datetime.now().year + 1)
    ]


def get_timestamp_path(instance, filename):
    return f'{datetime.datetime.now().timestamp()}{splitext(filename)[1]}'


signer = Signer()


def set_host():
    if ALLOWED_HOSTS:
        return 'http://' + ALLOWED_HOSTS[0]
    else:
        return 'http://localhost:8000'


def send_activation_notification(user):
    context = {
        'user': user,
        'host': set_host(),
        'sign': signer.sign(
            user.username)  # Создание уникальной цифровой подписи пользователя
Esempio n. 30
0
 def get_signer(cls):
     signer = Signer(salt=f"oscarapicheckout.{cls.__name__}")
     print(f"salt == oscarapicheckout.{cls.__name__}")
     return signer