Esempio n. 1
0
def send_create_account_email(email):
    """Sends an email through GovNotify to the specified address with an encoded link to verify their email

    :param email: The email address to send to
    """
    url_safe_serializer = URLSafeSerializer(app.config["SECRET_KEY"])

    response = uaa_controller.get_user_by_email(email)
    if response is None:
        return render_template("request-new-account-error.html")

    if response["totalResults"] == 0:
        internal_url = app.config["RESPONSE_OPERATIONS_UI_URL"]
        verification_url = f"{internal_url}/account/create-account/{token_decoder.generate_email_token(email)}"

        logger.info("Sending create account email", verification_url=verification_url)

        personalisation = {"CREATE_ACCOUNT_URL": verification_url, "EMAIL": email}

        try:
            NotifyController().request_to_notify(
                email=email, template_name="request_create_account", personalisation=personalisation
            )
        except NotifyError as e:
            logger.error("Error sending create account request email to Notify Gateway", msg=e.description)
            return render_template("request-new-account-error.html")

        logger.info("Successfully sent create account request email", encoded_email=url_safe_serializer.dumps(email))
    else:
        logger.info(
            "Requested account creation for email already in UAA", encoded_email=url_safe_serializer.dumps(email)
        )
        return render_template("request-new-account-exists.html", email=email)

    return render_template("request-new-account-check-email.html", email=email)
Esempio n. 2
0
def request_token():
    data = request.get_json(force=True)
    if data.get('type', '') not in ('deliver', 'company'):
        return bad_request('')
    s = Serializer(current_app.config['SECRET_KEY'])
    if data['type'] == 'deliver':
        phone_number = data.get('phone_number', '')
        device_id = data.get('device_id', '')
        if not (phone_number and device_id):
            return bad_request('')
        deliver_ = Deliver.query.filter(
            Deliver.phone_number == phone_number).first()
        if not deliver_:
            deliver_ = Deliver()
            deliver_.phone_number = phone_number
            deliver_.device_id = device_id
        else:
            deliver_.device_id = device_id
        db.session.add(deliver_)
        db.session.commit()
        token_ = s.dumps({
            'type': data['type'],
            'phone_number': phone_number
        }).decode('utf-8')
    else:
        company_id = data.get('company_id', '')
        if not company_id:
            return bad_request('')
        token_ = s.dumps({
            'type': data['type'],
            'company_id': company_id
        }).decode('utf-8')
    return {'token': token_}
Esempio n. 3
0
def get_api_key(request):
    s1 = URLSafeSerializer(settings.API_SECRET, salt="rolf-ipaddress-key")
    k1 = s1.dumps(dict(username=request.user.username, remote_addr=request.META["REMOTE_ADDR"]))
    s2 = URLSafeTimedSerializer(settings.API_SECRET, salt="rolf-timed-key")
    k2 = s2.dumps(dict(username=request.user.username))

    k3 = None
    ip = request.GET.get("ip", None)
    if ip:
        k3 = s1.dumps(dict(username=request.user.username, remote_addr=ip))
    return dict(k1=k1, k2=k2, k3=k3, ip=ip, remote_addr=request.META["REMOTE_ADDR"])
Esempio n. 4
0
def get_api_key(request):
    s1 = URLSafeSerializer(settings.API_SECRET, salt="rolf-ipaddress-key")
    k1 = s1.dumps(dict(username=request.user.username,
                       remote_addr=request.META['REMOTE_ADDR']))
    s2 = URLSafeTimedSerializer(settings.API_SECRET, salt="rolf-timed-key")
    k2 = s2.dumps(dict(username=request.user.username))

    k3 = None
    ip = request.GET.get('ip', None)
    if ip:
        k3 = s1.dumps(dict(username=request.user.username, remote_addr=ip))
    return dict(k1=k1, k2=k2, k3=k3, ip=ip,
                remote_addr=request.META['REMOTE_ADDR'])
def main():
    abspath = os.path.abspath(__file__)
    dname = os.path.dirname(abspath)
    os.chdir(dname)

    action = sys.argv[1]
    secret_key = sys.argv[2]

    if action == "generate":
        filename = sys.argv[3]
        basename = filename.split(".")[-2]
        extension = filename.split(".")[-1]
        digest = hashlib.sha512(secret_key + basename).hexdigest()
        des = URLSafeSerializer(digest)
        credentials = {
            'filename': filename.encode("base64"),
            'ext': extension,
            'length': len(filename),
            'signature': digest
        }
        print des.dumps(credentials, salt="donttread")
        return

    signed_serial = sys.argv[3]

    result = URLSafeSerializer("").loads_unsafe(signed_serial)

    img = "snek.jpg"

    try:
        if result[1]:
            signature = result[1]['signature']
            extension = result[1]['ext']
            filename = result[1]['filename'].decode("base64")
            length = result[1]['length']
            if len(filename) == length and len(extension) == 3:
                basename = filename.split(".")[-2]
                digest = hashlib.sha512(secret_key +
                                        splitext(filename)[0]).hexdigest()
                if digest == signature:
                    des = URLSafeSerializer(digest)
                    des.loads(signed_serial, salt="donttread")
                    img = "%s.%s" % (basename, extension)
    except:
        pass

    proc = subprocess.Popen(["./read_file", img], stdout=subprocess.PIPE)
    imgo = proc.stdout.read().encode("base64").replace("\n", "")
    output = '<img src="data:image/png;base64,%s" alt="i am %s" />' % (imgo,
                                                                       img)
    print output
Esempio n. 6
0
def get_private_alert_token(uid, send_id):
    signer = URLSafeSerializer(current_app.secret_key)
    return signer.dumps({
        'user': uid,
        'send': send_id,
    },
                        salt='private_alert_token')
Esempio n. 7
0
class SendEmail(object):
    def __init__(self):
        self.serial = URLSafeSerializer(app.config["SECRET_KEY"])
        self.sg = SGMail
        self.template = os.path.dirname(
            __file__) + "/templates/email_template.html"

    def send_invite_email(self, sender, league, to_email):
        j2_env = jinja2.Environment(
            loader=jinja2.PackageLoader('MovieLeague', 'templates'))
        template = j2_env.get_template('email_template.html')
        from_email = Email("*****@*****.**")
        to_email = Email(to_email)
        subject = "Invite to join %s" % league
        html = template.render(sender=sender,
                               league=league,
                               token=self.token_dump(league))
        content = Content("text/html", html)
        mail = Mail(from_email, subject, to_email, content)
        response = self.sg.client.mail.send.post(request_body=mail.get())
        print(response.status_code)
        print(response.body)
        print(response.headers)

    def token_dump(self, data):
        return self.serial.dumps(data)

    def token_load(self, token):
        return self.serial.loads(token)
Esempio n. 8
0
    def test_user_signin(self):
        """Tests if a user can signin and get a auth token."""
        data = dumps({
            'first_name': 'abc',
            'last_name': 'def',
            'email': '*****@*****.**',
            'password': '******'
        })
        self.create_new_user(data)

        response = self.client.post('/users/signin',
                                    data=dumps({
                                        'email': '*****@*****.**',
                                        'password': '******'
                                    }),
                                    content_type='application/json')

        # Generate token and compare with the one returned by the API.
        s = URLSafeSerializer(CONFIG.SECRET_KEY)
        token = s.dumps('*****@*****.**')

        self.assertEqual(
            loads(response.data), {
                'email': '*****@*****.**',
                'first_name': 'abc',
                'last_name': 'def',
                'message': 'User Authenticated Succesfully',
                'token': token
            })
Esempio n. 9
0
    def post(self):

        data = request.get_json(force=True)
        data = json.loads(data)

        if not request.json:
            abort(400, 'Invalid JSON Type')

        if not 'username' in request.json or not 'password' in request.json:
            return bad_request('Invalid JSON Key')
        active = dbcon.query.filter_by(email=data['username']).first()
        # checking for active state of the user
        if active:
            if not data or not data['username'] or not data['password']:
                return bad_request403('Login required')

            # checking for username availability
            if active.user_active:
                return bad_request403('User already logged in')

            # verifying password
            if check_password_hash(active.password, data['password']):
                s = URLSafeSerializer(app.config['SECRET'],
                                      salt='activate-salt')  # Token creation
                active.user_active = 1
                db.session.commit()
                respdata = {
                    'userID': active.user_no,
                    'token': s.dumps({'email': active.email})
                }
                return success_response(200, 'Login Success', respdata)
            return bad_request403('Authentication failed! wrong password')
        else:
            return bad_request403('User not exists')
Esempio n. 10
0
def notify_signup_accepted(event, signup):
    """Send an email to a user that his signup was accepted"""
    id_field = current_app.config['ID_FIELD']

    if signup.get('user'):
        lookup = {id_field: signup['user']}
        user = current_app.data.find_one('users', None, **lookup)
        name = user['firstname']
        email = user['email']
    else:
        name = 'Guest of AMIV'
        email = signup['email']

    s = URLSafeSerializer(get_token_secret())
    token = s.dumps(str(signup[id_field]))

    if current_app.config.get('SERVER_NAME') is None:
        current_app.logger.warning("SERVER_NAME is not set. E-Mail links "
                                   "will not work!")

    deletion_link = url_for('emails.on_delete_signup', token=token,
                            _external=True)

    mail([email],
         'Eventsignup accepted',
         current_app.config['ACCEPT_EMAIL_TEXT'].format(
             name=name,
             title=event.get('title_en') or event.get('title_de'),
             link=deletion_link,
             deadline=event['time_register_end'].strftime('%H.%M %d.%m.%Y')))
Esempio n. 11
0
def send_booking_mail(request, user, event):
    user_id = user.id
    event_id = event.id

    serial = URLSafeSerializer('some_secret_key', salt='cancel_reservation')
    data = {'event_id': event_id, 'user_id': user_id}

    cancel_token = serial.dumps(data)
    cancel_url = reverse('cancel_reservation', args=[cancel_token])
    cancel_url = request.build_absolute_uri(cancel_url)

    event_url = reverse('event_detail', args=[event_id, event.slug])
    event_url = request.build_absolute_uri(event_url)

    params = {'cancel_url': cancel_url, 'event_url': event_url, 'event': event}

    msg_plain = render_to_string('mail/relance.html', params)
    msg_html = render_to_string('mail/relance.html', params)

    date = event.starts_at.date().strftime("%d %B")
    location = event.location.name
    subject = "Votre réservation pour le " + date + " à " + location

    mail.send([user.email],
              '*****@*****.**',
              subject=subject,
              message=msg_plain,
              html_message=msg_html)
Esempio n. 12
0
def login_as_user(id):
    s = URLSafeSerializer(app.config['SECRET_KEY'])
    payload = {"id": id, "stamp": time.time()}
    token = s.dumps(payload)
    pieces = [app.config["LIME_URL"], 'trowel', token]
    url = '/'.join(piece.strip('/') for piece in pieces)
    return redirect(url)
Esempio n. 13
0
def send_confirmmail_to_unregistered_users(items):
    """Send a confirmation email for external signups(email only)

    Args:
        item: The item, which was just inserted into the database
    """
    for item in items:
        if 'user' not in item:
            event = current_app.data.find_one(
                'events', None,
                **{current_app.config['ID_FIELD']: item['event']})

            title = event.get('title_en') or event.get('title_de')

            s = URLSafeSerializer(get_token_secret())
            token = s.dumps(str(item['_id']))

            if current_app.config.get('SERVER_NAME') is None:
                current_app.logger.warning("SERVER_NAME is not set. E-Mail "
                                           "links will not work!")

            confirm_link = url_for('emails.on_confirm_email', token=token,
                                   _external=True)

            mail([item['email']],
                 'Registration for %s' % title,
                 current_app.config['CONFIRM_EMAIL_TEXT'].format(
                     title=title,
                     link=confirm_link))
Esempio n. 14
0
def send_confirmmail_to_unregistered_users(items):
    """Send a confirmation email for external signups(email only)

    Args:
        item: The item, which was just inserted into the database
    """
    for item in items:
        if item.get('user') is None:
            event = current_app.data.find_one(
                'events', None,
                **{current_app.config['ID_FIELD']: item['event']})

            title = event.get('title_en') or event.get('title_de')

            s = URLSafeSerializer(get_token_secret())
            token = s.dumps(str(item['_id']))

            if current_app.config.get('SERVER_NAME') is None:
                current_app.logger.warning("SERVER_NAME is not set. E-Mail "
                                           "links will not work!")

            confirm_link = url_for('emails.on_confirm_email',
                                   token=token,
                                   _external=True)

            mail([item['email']], 'Registration for %s' % title,
                 current_app.config['CONFIRM_EMAIL_TEXT'].format(
                     title=title, link=confirm_link))
Esempio n. 15
0
def create_targeted_device_sharing_token(device_id,
                                         access_level_id,
                                         account_id=None):
    """
    Creates device sharing token that can be passed only to account with passed
    id in order to allow access to device

    :param device_id: Id of device
    :type device_id: int
    :param access_level_id: Id of access level this link will give
    :type access_level_id: int
    :param account_id: Id of account
    :type account_id: int
    :raises: ValueError if device does not exist
    """
    if not Device.exists(id=device_id):
        raise NotPresentError("Device does not exist!")
    if not AccessLevel.exists(id=access_level_id):
        raise NotPresentError("AccessLevel does not exist!")

    data_to_serialize = {
        'device_id': device_id,
        'access_level_id': access_level_id
    }

    if account_id is not None:
        data_to_serialize['account_id'] = account_id

    serializer = URLSafeSerializer(app.config['SECRET_KEY'],
                                   salt=app.config['SECURITY_PASSWORD_SALT'])
    token = serializer.dumps(data_to_serialize)
    return token
Esempio n. 16
0
def resetpassword():
    form = PasswordResetForm()
    if form.validate_on_submit():
        if form.username.data:
            user = Users.query.filter_by(username=form.username.data).first()
        elif form.email.data:
            user = Users.query.filter_by(email=form.email.data).first()
        else:
            flash("Username or password doesn't exists")

        if user:
            if user.email:
                s = URLSafeSerializer('serliaizer_code')
                key = s.dumps([user.username, user.email])

            msg = Message("Password reset", sender="your_id@your_host.com", recipients=[user.email])
            msg.html = "<b>Click on this link to reset your password.</b> \
                        #<a href='http://127.0.0.1:5000/passwordreset/ \
                        " + key + "'>http://127.0.0.1:5000/passwordreset/ \
                        " + key + "</a>"

            send_async_email(msg)
            
            flash('Email sent to: ' + user.email)
            return redirect(url_for('resetpassword'))
        else:
            flash('No such user')
            return redirect(url_for('resetpassword'))
    flash(u'Enter your email or username')
    return render_template('reset_password.html', form=form)
Esempio n. 17
0
 def generate_auth_token(self):
     if self.id:
         s = Serializer(app.secret_key)
         return s.dumps(str(self.id))
     else:
         raise ValueError(
             'APIKey must be saved before requesting an auth token.')
Esempio n. 18
0
    def post(self):
        '''Adds a new user'''
        args = self.parser.parse_args()

        password = args.pop('password')
        new_user = User(**args)
        new_user.set_password(password)
        db.session.add(new_user)

        try:
            db.session.commit()
        except IntegrityError as e:
            if 'UNIQUE constraint failed: users.email' in str(e):
                json_abort(422, message='email_taken')
            else:
                raise
        finally:
            db.session.rollback()

        # send email verification link
        ts = URLSafeSerializer(current_app.config["SECRET_KEY"],
                               salt='verify-email')
        token = ts.dumps(new_user.id)
        link = ext_url_for('auth.verify_email', token=token)

        send_email(
            new_user.email, 'Registrierung bei Supermarkt abschließen',
            render_template('registration.txt',
                            validation_link=link,
                            name=new_user.name))

        return dict(message='verify_email', user=new_user.as_dict()), 201
Esempio n. 19
0
File: admin.py Progetto: wiota/lime
def send_invite(user):
    s = URLSafeSerializer(app.config['SECRET_KEY'])
    payload = s.dumps(str(user.id))
    link_href = url_for("root.confirm", payload=payload, _external=True)

    InviteEmail(user.email, link_href).send()
    flash("Successfully sent invitation.")
Esempio n. 20
0
 def save(self, *args, **kwargs):
     if self.pk is None:
         from itsdangerous import URLSafeSerializer
         s = URLSafeSerializer(SECRET_KEY)
         x = datetime.now()
         self.ss_id = s.dumps(str(x))
     super(Question, self).save(*args, **kwargs)
Esempio n. 21
0
def forgot_password():
    form = ForgotPasswordForm()
    if (form.validate_on_submit()):
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None:
            s = URLSafeSerializer(Config.SECRET_KEY)
            user.reset_password_token = s.dumps([user.id, user.password])
            db.session.commit()
            reset_link = url_for('public.reset_password',
                                 token=user.reset_password_token)
            email_message = '''Hello, you have requested a reset password token.
            Ignore this if you do not think you requested one.
            <a href="{}"> {}</a>'''
            email_message = email_message.format(reset_link, reset_link)
            return email_message
            msg = Message(email_message,
                          sender="*****@*****.**",
                          recipients=['*****@*****.**'])
            mail.send(msg)
            flash(
                "We have send a link to reset your password. Please check your email"
            )

            return redirect(url_for('public.index'))
        else:
            flash('no user found')
            return redirect(url_for('public.index'))
    return render_template('forgot-password.html', form=form)
Esempio n. 22
0
    def test_resetpassword_old_request(self):
        user = app_model.User(email_address='*****@*****.**',
                              user_name='test',
                              display_name='Test',
                              password='******')
        try:
            app_model.DBSession.add(user)
        except AttributeError:
            # Ming DBSession doesn't have/require .add
            pass
        old_password = user.password
        flush_db_changes()

        from datetime import datetime
        from dateutil.relativedelta import relativedelta
        old_date = datetime.utcnow() - relativedelta(years=3)
        import tg
        secret = tg.config.get('session.secret',
                               tg.config.get('beaker.session.secret'))
        from itsdangerous import URLSafeSerializer
        serializer = URLSafeSerializer(secret)
        serialized_data = serializer.dumps(
            dict(request_date=old_date.strftime('%m/%d/%Y %H:%M'),
                 email_address='*****@*****.**',
                 password_frag='eh',
                 redirect_to='/'))
        new_url = 'http://localhost/resetpassword/change_password/?data=' + serialized_data
        resp = self.app.get(new_url)
        form = resp.form
        form['password'] = '******'
        form['password_confirm'] = 'alfa'
        resp = form.submit()
        assert 'Password%20reset%20request%20timed%20out' in resp.headers[
            'Set-Cookie']
Esempio n. 23
0
def register():
    form = RegisterUserForm()
    if form.validate_on_submit():

        user = User.create(
            username=form.data['username'],
            email=form.data['email'],
            password=form.data['password'],
            remote_addr=request.remote_addr,
        )

        s = URLSafeSerializer(current_app.secret_key)
        token = s.dumps(user.id)

        send_registration_email.delay(
            {
                'username': user.username,
                'email': user.email
            }, token)

        flash(
            gettext(
                'Sent verification email to {email}'.format(email=user.email)),
            'success')
        return redirect(url_for('index'))
    return render_template('register.html', form=form)
Esempio n. 24
0
 def post(self, request):
     try:
         username = request.POST.get('username')
         password1 = request.POST.get('password1')
         password2 = request.POST.get('password2')
         email = request.POST.get('email')
         user = authenticate(username=username, password=password1)
         if user:
             # 用户已经存在
             return render(request, 'register.html', {'msg': '用户名已存在'})
         else:
             # 保存用户
             user = User.objects.create_user(username=username,
                                             password=password1,
                                             email=email,
                                             is_active=0)
             auth_s = URLSafeSerializer(settings.SECRET_KEY, "auth")
             token = auth_s.dumps({'name': username})
             cache.set(token, user.id, timeout=10 * 60)
             active_url = f'http://127.0.0.1:8000/active/?tooken={token}'
             content = loader.render_to_string('email.html',
                                               request=request,
                                               context={
                                                   'username': username,
                                                   'active_url': active_url
                                               })
             sendmail.delay(content)
             return redirect('/')
     except Exception as e:
         return render(request, 'register.html', {'msg': '注册失败'})
Esempio n. 25
0
def create_reset_link(user):
    l = "http://localhost:5001/reset/"
    s = URLSafeSerializer("hacker-bees")
    token = s.dumps(user.id)
    l += token
    user.reset_time = datetime.today()
    return l
Esempio n. 26
0
 def generate_client_token(self):
     """
     use client_id & client_key
     to generate client grant token
     """
     s = Serializer(current_app.config["SECRET_KEY"])
     return s.dumps({'client_id': self.id})
Esempio n. 27
0
def resetpassword():
    form = PasswordResetForm()
    if form.validate_on_submit():
        if form.username.data:
          user = Users.query.filter_by(username=form.username.data).first()
        elif form.email.data:
          user = Users.query.filter_by(email=form.email.data).first()
        else:
          flash("Username or password not in system")
          
        if user:
          if user.email:
            s = URLSafeSerializer('12fe454t')
            key = s.dumps([user.username, user.email])
            #s.loads('WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo')
            
            msg = Message("Password reset", sender="*****@*****.**", recipients=[user.email])
            msg.html = "<b>testing</b> \
                        #<a href='http://127.0.0.1:5000/passwordreset/" + key + "'>http://127.0.0.1:5000/passwordreset/" + key + "</a>"

            print msg.html
            mail.send(msg)
            
            flash('Email sent to: ' + user.email)
            return redirect(url_for('resetpassword'))
          else:
            flash('No such user')
            return redirect(url_for('resetpassword'))
        else:
            flash('No such user')
            return redirect(url_for('resetpassword'))

    return render_template('reset_password.html', form=form)
Esempio n. 28
0
def new_task(app_id):
    """Return a new task for an application."""
    # Check if the request has an arg:
    try:
        app = db.session.query(model.App).get(app_id)
        if app is None:
            raise NotFound
        if request.args.get('offset'):
            offset = int(request.args.get('offset'))
        else:
            offset = 0
        user_id = None if current_user.is_anonymous() else current_user.id
        user_ip = request.remote_addr if current_user.is_anonymous() else None
        task = sched.new_task(app_id, user_id, user_ip, offset)
        # If there is a task for the user, return it

        if task:
            s = URLSafeSerializer(current_app.config.get('SECRET_KEY'))
            r = make_response(json.dumps(task.dictize()))
            r.mimetype = "application/json"
            cookie_id = 'task_run_for_task_id_%s' % task.id
            r.set_cookie(cookie_id, s.dumps(task.dictize()))
            return r

        else:
            return Response(json.dumps({}), mimetype="application/json")
    except Exception as e:
        return error.format_exception(e, target='app', action='GET')
Esempio n. 29
0
def send_confirmation(email):
    serializer = URLSafeSerializer(admininfo.secret_key,
                                   salt=admininfo.confirm_salt)
    token = serializer.dumps(email)
    url = 'http://praxtrain.com/confirm/' + token

    text = generateEmail.generateConfText(url)
    html = generateEmail.generateConfHTML(url)

    sender = '*****@*****.**'

    smtpserver = smtplib.SMTP('smtp.zoho.com', 587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.login(sender, admininfo.zoho_pw)

    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Confirm your email subscription to PraxTrain"
    msg['From'] = 'DailyPrax <' + sender + '>'
    msg['To'] = email

    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    msg.attach(part1)
    msg.attach(part2)

    smtpserver.sendmail(sender, email, msg.as_string())
    print('Email sent to ' + email)

    smtpserver.quit()
Esempio n. 30
0
def create_new_profile(user_profile):
    token_signer = URLSafeSerializer(
        config_secrets["UUIDSECRET"]["secret_key"],
        salt=config_secrets["UUIDSECRET"]["secret_salt"])

    print("Creating a new entry for user!")

    # Generate New User ID --> Random and unique
    user_id = 'UI_' + str(uuid.uuid4())

    # Generate New User Token
    user_token = token_signer.dumps(user_id)

    # New User Record Structure
    new_user_profile = {
        'FACEBOOK_ID': user_profile['FACEBOOK_ID'],
        'USER_ID': user_id,
        'USER_NAME': user_profile['USER_NAME'],
        'EMAIL_ID': user_profile['EMAIL_ID'],
        'GENDER': user_profile['GENDER'],
        'USER_TOKEN': user_token,
        'FIREBASE_ID': user_profile['FIREBASE_ID']
    }

    user_profile_table.put_item(Item=new_user_profile)

    print("New entry created!")

    # ADD CODE TO CREATE RECORDS FOR FRIENDLIST, PREFERENCE, AND FEEDBACK
    # -------------------------------------------------------------------

    return user_token
class LinkGenerator:
    """
    Link to personalised form in email
    """
    DELIMITER = ';'

    def __init__(self, app):
        self._app = app
        self._serializer = URLSafeSerializer(app.config['SECRET_KEY'])

    def generate_payload(self, gala_id, club_id, swimmer_id):
        """
        Include identifiers in payload
        :param gala_id:
        :param club_id:
        :param swimmer_id:
        """
        payload = str(time()) + self.DELIMITER + str(gala_id) + self.DELIMITER + str(club_id) + \
                  self.DELIMITER + str(swimmer_id)
        return self._serializer.dumps(payload, salt=constants.LINK_GENERATOR_SALT)

    def load_payload(self, payload):
        """
        Retrieve identifiers from payload
        :param payload:
        """
        plain_payload = self._serializer.loads(payload, salt=constants.LINK_GENERATOR_SALT)
        try:
            plain_payload = plain_payload.split(self.DELIMITER)
            return {'gala_id': plain_payload[1], 'club_id': plain_payload[2], 'swimmer_id': plain_payload[3]}
        except:
            raise ValueError('Invalid payload format detected.')
Esempio n. 32
0
def generate_jwt(claims, lifetime=None, expires=None, not_before=None):
    """
    Generate a JSON Web Token.

    - **exp** (*IntDate*) -- The UTC expiry date and time of the token, in number of seconds from 1970-01-01T0:0:0Z UTC.
    - **iat** (*IntDate*) -- The UTC date and time at which the token was generated.
    - **nbf** (*IntDate*) -- The UTC valid-from date and time of the token.
    - **jti** (*str*) -- A unique identifier for the token.
    """
    claims = dict(claims)

    now = datetime.utcnow()

    claims['iat'] = timegm(now.utctimetuple())
    claims['nbf'] = timegm((not_before or now).utctimetuple())
    claims['jti'] = urlsafe_b64encode(urandom(128))

    if lifetime:
        claims['exp'] = timegm((now + lifetime).utctimetuple())
    elif expires:
        claims['exp'] = timegm(expires.utctimetuple())

    signer = URLSafeSerializer(SECRET_KEY)

    return signer.dumps(claims)
Esempio n. 33
0
 def get_context_data(self, **kwargs):
     context = super(AlbumView, self).get_context_data(**kwargs)
     serializer = URLSafeSerializer(settings.SECRET_KEY)
     token = serializer.dumps({'album_id': self.object.id})
     context['token'] = token
     context['album'] = self.object
     return context
Esempio n. 34
0
def resend_activation():
    """
    Resend the activation token in the user's email.
    returns: 403 if any errors occur. 200 if successful, and user get the
             activation mail resent to him.
    """
    req = request.get_json()

    try:
        user = (User.query
                .filter(User.email == req['email'])
                .one())

        if user.is_active:
            return Error("User is already active", 403)()

        serializer = URLSafeSerializer(app.config['SECRET_KEY'])
        activation_token = serializer.dumps(user.email)

        activation_url = url_for('User.activate_user',
                                 activation_token=activation_token,
                                 _external=True)

        Mail(req['email'],
             subject_data={'name': user.full_name},
             html_data={'token': activation_url},
             text_data={'name': user.full_name},
             template_root=SIGNUP_ACTIVATION
             ).send()

        return ""
    except NoResultFound:
        return Error("User with that email doesnt exist", 403)()
Esempio n. 35
0
def reset_password():
    form = PasswordResetForm()
    if form.validate_on_submit():
        if form.username.data:
            user = Users.query.filter_by(username=form.username.data).first()
        elif form.email.data:
            user = Users.query.filter_by(email=form.email.data).first()
        else:
            flash("Username or password doesn't exists")

        if user:
            if user.email:
                s = URLSafeSerializer('serliaizer_code')
                key = s.dumps([user.username, user.email])

            msg = Message("Password reset",
                          sender="your_id@your_host.com",
                          recipients=[user.email])
            msg.html = "<b>Click on this link to reset your password.</b> \
                        #<a href='http://127.0.0.1:5000/passwordreset/ \
                        " + key + "'>http://127.0.0.1:5000/passwordreset/ \
                        " + key + "</a>"

            send_async_email(msg)

            flash('Email sent to: ' + user.email)
            return redirect(url_for('reset_password'))
        else:
            flash('No such user')
            return redirect(url_for('reset_password'))
    flash(u'Enter your email or username')
    return render_template('reset_password.html', form=form)
Esempio n. 36
0
def register():
    form = RegisterUserForm()
    if form.validate_on_submit():

        user = User.create(
            username=form.data['username'],
            email=form.data['email'],
            password=form.data['password'],
            remote_addr=request.remote_addr,
        )

        s = URLSafeSerializer(current_app.secret_key)
        token = s.dumps(user.id)

        send_registration_email.delay(user, token)

        flash(
            gettext(
                'Sent verification email to {email}'.format(
                    email=user.email
                )
            ),
            'success'
        )
        return redirect(url_for('index'))
    return render_template('register.html', form=form)
Esempio n. 37
0
    def reset_request(self, **kw):
        user = model.provider.query(app_model.User, filters=dict(email_address=kw['email_address']))[1][0]
        password_frag = user.password[0:4]
        serializer = URLSafeSerializer(tg.config['beaker.session.secret'])
        serialized_data = serializer.dumps(dict(request_date=datetime.utcnow().strftime('%m/%d/%Y %H:%M'),
                                                email_address=kw['email_address'], password_frag=password_frag))

        password_reset_link = tg.url(self.mount_point + "/change_password/", params=dict(data=serialized_data),
                                     qualified=True)
        reset_password_config = tg.config.get('_pluggable_resetpassword_config')
        mail_body = reset_password_config.get('mail_body', _('''
We've received a request to reset the password for this account. 
Please click this link to reset your password:

%(password_reset_link)s

If you no longer wish to make the above change, or if you did not initiate this request, please disregard and/or delete this e-mail.
'''))

        email_data = {'sender': tg.config['resetpassword.email_sender'],
                      'subject': reset_password_config.get('mail_subject', _('Password reset request')),
                      'body': mail_body,
                      'rich': reset_password_config.get('mail_rich', '')}

        tg.hooks.notify('resetpassword.on_request', args=(user, email_data, password_reset_link))

        email_data['body'] = email_data['body'] % dict(password_reset_link=password_reset_link)
        email_data['rich'] = email_data['rich'] % dict(password_reset_link=password_reset_link)
        send_email(user.email_address, **email_data)
        flash(_('Password reset request sent'))
        return plug_redirect('resetpassword', '/')
Esempio n. 38
0
def generate_user_token(email, salt):
    with open('credentials.txt') as f:
        credentials = {k: v for k, v in map(str.split, f.readlines())}
        server_secret = credentials['SERVER_SECRET']

    serializer = URLSafeSerializer(server_secret, salt=salt)
    return serializer.dumps(email)
Esempio n. 39
0
def resend_activation_email(email_to_activate):
    """
    Function to resend the activation email
    """
    #check local database
    loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.username==email_to_activate) #@UndefinedVariable
    #get the user object
    user_rec = loc_db_user.first()
    if user_rec:
        #create an itsdangerous object to sign the verification email 
        itsd = URLSafeSerializer(config.ACCOUNT_VERIFICATION_SECRET)
        #send the confirmation email
        act_code = itsd.dumps(email_to_activate)
        message_html = """<h3>Dear %(name)s %(lastname)s, thank you for registering to the NASA ADS</h3>
                            <p>Your activation code is <strong>%(code)s</strong></p>
                            <p>To activate your account, please click <a href="%(act_url)s">here</a></p>
                            <p>If the link doesn't work, please copy the following URL and paste it in your browser:<br/>%(act_url)s</p>
                            <p>Please do not replay to this email: to contact us please use our <a href="%(feedb_url)s">feedback form</a></p>
                            <p>Regards,<br/>The ADS team</p>
                        """ % {'name':user_rec.firstname, 'lastname':user_rec.lastname, 'code':act_code, 
                               'act_url': '%s%s?id=%s' % (config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('user.activate'), act_code),
                               'feedb_url' : '%s%s'%(config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('feedback.feedback'))
                               }
        try:
            send_email_to_user(u"NASA ADS Account confirmation required", message_html, [email_to_activate])
        except:
            app.logger.error('Failed to re-send confirmation email for user creation')
            return False, 'There are some technical problems: please try later.', 'error'
        return True, 'A new email with the activation code has been sent to your email address.', 'success'
    else:
        app.logger.error('Tried to re-send confirmation email for user creation for user not yet created or not stored in the DB. Email used %s' % email_to_activate)
        return False, 'The user with the given email does not exist', 'error'
Esempio n. 40
0
def new_task(app_id):
    # Check if the request has an arg:
    try:
        app = db.session.query(model.App).get(app_id)
        if app is None:
            raise NotFound
        if request.args.get('offset'):
            offset = int(request.args.get('offset'))
        else:
            offset = 0
        user_id = None if current_user.is_anonymous() else current_user.id
        user_ip = request.remote_addr if current_user.is_anonymous() else None
        task = sched.new_task(app_id, user_id, user_ip, offset)
        # If there is a task for the user, return it

        if task:
            s = URLSafeSerializer(current_app.config.get('SECRET_KEY'))
            r = make_response(json.dumps(task.dictize()))
            r.mimetype = "application/json"
            cookie_id = 'task_run_for_task_id_%s' % task.id
            r.set_cookie(cookie_id, s.dumps(task.dictize()))
            return r

        else:
            return Response(json.dumps({}), mimetype="application/json")
    except Exception as e:
        return error.format_exception(e, target='app', action='GET')
Esempio n. 41
0
class Serializer:
    def __init__(self, app):
        self.serializer = URLSafeSerializer(app.config['SECRET_KEY'])
        self.salt = app.config['SECRET_SALT']

    def loads(self, token):
        return self.serializer.loads(token)

    def dumps(self, string):
        return self.serializer.dumps(string)

    def loads_salted(self, token):
        return self.serializer.loads(token, salt=self.salt)

    def dumps_salted(self, string):
        return self.serializer.dumps(string, salt=self.salt)
Esempio n. 42
0
 def save(self, *args, **kwargs):
     from itsdangerous import URLSafeSerializer
     s = URLSafeSerializer(SECRET_KEY)
     x = datetime.now()
     self.ss_id = s.dumps(str(x))
     if self.pk is None:
         super(Question, self).save(self, *args, **kwargs)
Esempio n. 43
0
 def generate_auth_token(self):
     """generate a token"""
     s = Serializer(
         current_app.config['SECRET_KEY']
         # expiration
     )
     return s.dumps({'id': self.id})
Esempio n. 44
0
 def generate_auth_token(self):
     """generate a token"""
     s = Serializer(
         current_app.config['SECRET_KEY']
         # expiration
     )
     return s.dumps({'id': self.id})
Esempio n. 45
0
def toggle_choice(request):
    campaign = get_active_campaign_or_404()
    volunteer = get_object_or_404(Volunteer, pk=request.POST.get('volunteer_id'))

    with transaction.atomic():
        cursor = connection.cursor()
        cursor.execute('LOCK TABLE %s' % VolunteerCampaign._meta.db_table)

        created = False

        try:
            obj = VolunteerCampaign.objects.get(
                Q(accepted__isnull=True) | Q(accepted=True),
                campaign=campaign, volunteer=volunteer,
            )
        except VolunteerCampaign.DoesNotExist:
            obj, created = VolunteerCampaign.objects.get_or_create(
                campaign=campaign, volunteer=volunteer,
                organisation=request.user.organisation,
            )

        if created:
            serializer = URLSafeSerializer(settings.SECRET_KEY)
            confirm_invite_url = reverse('confirm_invite', args=[serializer.dumps(obj.pk)])
            get_adapter().send_mail('emails/volunteer_invitation', volunteer.user.email, {
                'organisation': request.user.organisation,
                'confirm_invite_url': request.build_absolute_uri(confirm_invite_url),
            })

    state, label = get_volunteer_status(obj, request.user.organisation)

    return JsonResponse({
        'state': state,
        'label': label,
    })
Esempio n. 46
0
def forgot_password():
    """
    Sends Reset Password link to User's email address. User can change
    his/her password through the link mentioned in the Email. It won't be an
    endpoint, it will be a webpage
    :return: 403 if any errors, else return 200
    """
    req = request.get_json()

    serializer = URLSafeSerializer(app.config['SECRET_KEY'])

    try:
        user = User.query \
            .filter(User.email == req['email']) \
            .filter(User.is_active) \
            .one()

        token = serializer.dumps(req['email'])
        reset_password_link = f"{request.url_root}reset_password?token={token}"

        Mail(user.email,
             subject_data={'name': user.full_name},
             html_data={'token': reset_password_link},
             text_data={'token': reset_password_link},
             template_root=FORGOT_PASSWORD
             ).send()

        return ""
    except NoResultFound:
        return Error('Invalid Email Address', 403)()
def main():
    abspath = os.path.abspath(__file__)
    dname = os.path.dirname(abspath)
    os.chdir(dname)

    action = sys.argv[1]
    secret_key = sys.argv[2]

    if action == "generate":
        filename = sys.argv[3]
        basename = filename.split(".")[-2]
        extension = filename.split(".")[-1]
        digest = hashlib.sha512(secret_key + basename).hexdigest()
        des = URLSafeSerializer(digest)
        credentials = {'filename': filename.encode("base64"),
                       'ext': extension,
                       'length': len(filename),
                       'signature': digest}
        print des.dumps(credentials, salt="donttread")
        return

    signed_serial = sys.argv[3]

    result = URLSafeSerializer("").loads_unsafe(signed_serial)

    img = "snek.jpg"

    try:
        if result[1]:
            signature = result[1]['signature']
            extension = result[1]['ext']
            filename  = result[1]['filename'].decode("base64")
            length    = result[1]['length']
            if len(filename) == length and len(extension) == 3:
                basename = filename.split(".")[-2]
                digest = hashlib.sha512(secret_key + splitext(filename)[0]).hexdigest()
                if digest == signature:
                    des = URLSafeSerializer(digest)
                    des.loads(signed_serial, salt="donttread")
                    img = "%s.%s" % (basename, extension)
    except:
        pass

    proc = subprocess.Popen(["./read_file", img], stdout=subprocess.PIPE)
    imgo = proc.stdout.read().encode("base64").replace("\n", "")
    output = '<img src="data:image/png;base64,%s" alt="i am %s" />' % (imgo, img)
    print output
Esempio n. 48
0
File: views.py Progetto: ccnmtl/rolf
def get_api_key(request):
    remote_addr = request.META.get(
        'HTTP_X_FORWARDED_FOR',
        request.META.get('REMOTE_ADDR'))
    s1 = URLSafeSerializer(settings.API_SECRET, salt="rolf-ipaddress-key")
    k1 = s1.dumps(dict(username=request.user.username,
                       remote_addr=remote_addr))
    s2 = URLSafeTimedSerializer(settings.API_SECRET, salt="rolf-timed-key")
    k2 = s2.dumps(dict(username=request.user.username))

    k3 = None
    ip = request.GET.get('ip', None)
    if ip:
        k3 = s1.dumps(dict(username=request.user.username, remote_addr=ip))
    return render(request, 'rolf/get_api_key.html',
                  dict(k1=k1, k2=k2, k3=k3, ip=ip,
                       remote_addr=remote_addr))
Esempio n. 49
0
 def encrypt(self, payload, timestamp=False):
     result = ''
     s1 = URLSafeSerializer(self.secret_key)
     result = s1.dumps(payload)
     if(timestamp == True):
         s2 = TimestampSigner(self.secret_key)
         result = s2.sign(result)
     return result
Esempio n. 50
0
 def save(self, *args, **kwargs):
     from itsdangerous import URLSafeSerializer
     s = URLSafeSerializer(SECRET_KEY)
     x = Test.objects.all().count()
     print(x)
     print(type(x))
     self.s_id = s.dumps(x + 1)
     if self.pk is None:
         super(Test, self).save(self, *args, **kwargs)
Esempio n. 51
0
 def __generate_key(string):
     app = current_app._get_current_object()
     s = URLSafeSerializer(app.config['SECRET_KEY'])
     string = '%s.%s.%s' % (string, time.time(), random.getrandbits(256))
     string = sha256(string).hexdigest()
     string = s.dumps(string)
     # return base64.b64encode(sha1(string).hexdigest(),
     #                         ).rstrip('==')
     return sha1(string).hexdigest()
Esempio n. 52
0
def generate_confirmation_token(email):
    """
    Generates a confirmation token for the user to confirm their account
    The actual email is encoded in the token
    :param email: The user email
    :return:
    """
    serializer = URLSafeSerializer(current_app.config.get("SECRET_KEY"))
    return serializer.dumps(email, salt=current_app.config.get("SECURITY_PASSWORD_SALT"))
Esempio n. 53
0
    def send_activation_email(self):
        s = URLSafeSerializer(app.config['SECRET_KEY'])
        payload = s.dumps(self.username)
        url = url_for('activate', payload=payload, _external=True)

        subject = "Activate your account"
        text = render_template("activate.txt", url=url)
        html = render_template("activate.html", url=url)
        email_helper.send_email(self.get_email(), subject, text, html)
Esempio n. 54
0
 def generate_client_token(self):
     """
     use client_id & client_key
     to generate client grant token
     """
     s = Serializer(
         current_app.config["SECRET_KEY"]
     )
     return s.dumps({'client_id': self.id})
Esempio n. 55
0
class Encryption:
    def init_app(self, app):
        self.serializer = URLSafeSerializer(app.config.get('SECRET_KEY'))
        self.salt = app.config.get('DANGEROUS_SALT')

    def encrypt(self, thing_to_encrypt):
        return self.serializer.dumps(thing_to_encrypt, salt=self.salt)

    def decrypt(self, thing_to_decrypt):
        return self.serializer.loads(thing_to_decrypt, salt=self.salt)
Esempio n. 56
0
def _generate_signed_string(payload):
    """

    :param payload:
    :return:
    """
    signer_kwargs = {"digest_method": sha256}
    signer = URLSafeSerializer(app.secret_key, signer_kwargs=signer_kwargs)
    signature = signer.dumps(payload)
    return signature
Esempio n. 57
0
def create_user(signup_form):
    """
    Function that inserts the user info in the local database before being activated
    and sends an email with the confirmation code
    """
    # create an itsdangerous object to sign the verification email and encrypt the password
    itsd = URLSafeSerializer(config.ACCOUNT_VERIFICATION_SECRET)

    # send the confirmation email
    act_code = itsd.dumps(signup_form.login.data)
    message_html = """<h3>Dear %(name)s %(lastname)s, thank you for registering to the NASA ADS</h3>
                        <p>Your activation code is <strong>%(code)s</strong></p>
                        <p>To activate your account, please click <a href="%(act_url)s">here</a></p>
                        <p>If the link doesn't work, please copy the following URL and paste it in your browser:<br/>%(act_url)s</p>
                        <p>Please do not replay to this email: to contact us please use our <a href="%(feedb_url)s">feedback form</a></p>
                        <p>Regards,<br/>The ADS team</p>
                    """ % {
        "name": signup_form.name.data,
        "lastname": signup_form.lastname.data,
        "code": act_code,
        "act_url": "%s%s?id=%s" % (config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for("user.activate"), act_code),
        "feedb_url": "%s%s" % (config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for("feedback.feedback")),
    }
    try:
        send_email_to_user(u"NASA ADS Account confirmation required", message_html, [signup_form.login.data])
    except:
        app.logger.error("Failed to send confirmation email for user creation")
        return False, "There are some technical problems: please try later.", "error"

    # create a new user object
    new_rec = AdsUserRecord(
        cookie_id=g.user_cookie_id,  # temporary unique cookie id
        username=signup_form.login.data,
        firstname=signup_form.name.data,
        lastname=signup_form.lastname.data,
        password=itsd.dumps(signup_form.password.data),
        registered=datetime.utcnow().replace(tzinfo=pytz.utc),
        active=False,
        anonymous=False,
    )
    # save the user
    new_rec.save()
    return True, "Thanks for the registration. An email with the activation code has been sent to you.", "success"
Esempio n. 58
0
File: main.py Progetto: kdwarn/wyr
def change_password():
    ''' Let users change password '''

    if request.method == 'GET':
        return render_template('change_password.html')
    elif request.method == 'POST':
        if request.form['submit'] == 'Cancel':
            flash('Password change cancelled.')
            return redirect(url_for('main.settings'))

        current_password = request.form['wyr_current_password']
        new_password = request.form['wyr_new_password']
        confirm_password = request.form['wyr_confirm_password']

        #first verify current password
        myctx = CryptContext(schemes=['pbkdf2_sha256'])
        if myctx.verify(current_password, current_user.password) == True:
            #password checks
            if len(new_password) < 5:
                flash('Password is too short. Please try again.')
                return redirect(url_for('main.change_password'))
            elif new_password != confirm_password:
                flash('The confirmation password did not match the new password you entered.')
                return redirect(url_for('main.change_password'))
            else:
                #use passlib to encrypt password
                myctx = CryptContext(schemes=['pbkdf2_sha256'])
                hash = myctx.encrypt(new_password)

                current_user.password = hash
                db.session.commit()

                # send user email to confirm, allow reset of password
                #hash for confirm change
                serializer = URLSafeSerializer(current_app.config['SECRET_KEY'])
                email_hash = serializer.dumps([current_user.email], salt='reset_password')

                to = current_user.email
                subject = 'Password Change'
                text = """The password for your What You've Read account has been
                changed. If this was not you, someone has access to your account. You should
                <a href="http://www.whatyouveread.com/reset_password?code={}">reset your
                password</a> immediately.<br>
                <br>
                -Kris @ What You've Read""".format(email_hash)

                common.send_simple_message(to, subject, text)

                flash('Your password has been updated.')
                return redirect(url_for('main.settings'))
        else:
            flash('Password is incorrect.')
            return redirect(url_for('main.change_password'))
    else:
        return abort(405)
Esempio n. 59
0
def email_verify(username, email):
    s = URLSafeSerializer(secret_key, salt=email_verify_salt)
    token = s.dumps(
        dict(
            u=username,
            e=email))
    url = 'http://www.genitag.org/action/accountverify?token=' + token
    subject = 'Verify email for Genitag account'
    message = 'visit this link to verify your email address to the account with the username ' \
              + username + '\r\n' + 'link: ' + url
    send_email(message, subject, email)
    return None