def update_user_password():
    email = request.form.get('email')
    if not email:
        return 'Bad Request', 404
    signed_data = request.headers['Authorisation']
    client_key = app.config['WWW_CLIENT_KEY']
    signer = TimestampSigner(client_key, digest_method=hashlib.sha256)
    try:
        unsigned = signer.unsign(signed_data, max_age=5)
        client_id, user_email, password = unsigned.decode('utf-8').split(':')
        if client_id != app.config['WWW_CLIENT_ID']:
            raise Exception
        if email != user_email:
            raise Exception

        user = AuthUser.objects.filter(email=email).first()
        if not user:
            abort(404)
        else:
            user.set_password(password)
            user.save()
            return 'OK', 200

    except Exception as ex:
        log_traceback(current_app.logger, ex)
        return 'Unauthorized', 401
Beispiel #2
0
def verifyCdata(cdata, secretkey, mxtime):
  s = TimestampSigner(secretkey)
  try: 
    string = s.unsign(cdata, max_age=mxtime)
    return string 
  except: 
    return False
def register_user():
    data = request.form
    if not (data['full_name'] or data['email']):
        return 'Bad Request', 404
    signed_data = request.headers['Authorisation']
    client_key = app.config['WWW_CLIENT_KEY']
    signer = TimestampSigner(client_key, digest_method=hashlib.sha256)
    try:
        unsigned = signer.unsign(signed_data, max_age=5)
        client_id, email, full_name = unsigned.decode('utf-8').split(':')
        if client_id != app.config['WWW_CLIENT_ID']:
            raise Exception
        if email != data['email']:
            raise Exception
        if full_name != data['full_name']:
            raise Exception
    except Exception as ex:
        log_traceback(current_app.logger, ex)
        return 'Unauthorized', 401

    person = registers.Person()
    person.born_at = datetime.fromtimestamp(mktime(gmtime(0)))
    person.full_name = full_name
    person.save()

    random_temp_password = uuid4().hex
    user = auth.AuthUser.create_user(email, random_temp_password)
    user.person_uri = person.uri
    user.save()

    return 'Created', 201
Beispiel #4
0
def email_check():
    """
    校验邮箱有效性
    http://localhost:5000/email/[email protected]
    """
    sign = request.args.get('sign', '')
    from itsdangerous import TimestampSigner, SignatureExpired, BadTimeSignature
    s = TimestampSigner(app.config['SECRET_KEY'])
    try:
        # email = s.unsign(sign, max_age=5)  # 5秒过期
        email = s.unsign(sign, max_age=30*24*60*60)  # 1个月过期
        # return email
        # 校验通过,更新邮箱验证状态
        from user_auth import update_user_auth_rows
        result = update_user_auth_rows({'verified': 1}, **{'auth_type': 'email', 'auth_key': email})
        if result == 1:
            flash(u'%s, Your mailbox has been verified' % email, 'success')
            return redirect(url_for('login'))
        else:
            flash(u'%s, Sorry, Your mailbox validation failed' % email, 'warning')
    except SignatureExpired as e:
        # 处理签名超时
        flash(e.message, 'warning')
    except BadTimeSignature as e:
        # 处理签名错误
        flash(e.message, 'warning')
    return redirect(url_for('reg'))
Beispiel #5
0
 def get(self):
     args = get_parser('activation').parse_args()
     serial = args['serial']
     change_email = redis.get('change_email:{}'.format(serial))
     if not change_email:
         return make_response(redirect('/#!/?error=激活码无效'))
     change_email = change_email.decode()
     signer = TimestampSigner(
         current_app.config['SECRET_KEY'], salt='change_email')
     try:
         username = signer.unsign(
             base64.b64decode(serial.encode('utf-8')),
             max_age=172800).decode('utf-8')
         user = User.query.filter_by(username=username).first()
         if not user:
             return make_response(redirect('/#!/?error=激活码无效'))
         authentication = db_session.query(Authentication).filter(
             AuthenticationType.logic == 'email',
             Authentication.type_id == AuthenticationType.id,
             Authentication.user_id == user.id).first()
         authentication.accept()
         authentication.fields[0].value = change_email
         user.email = change_email
         redis.delete('change_email:{}'.format(serial))
         db_session.commit()
     except (itsdangerous.BadSignature, itsdangerous.SignatureExpired):
         abort(400, message='激活码无效')
     else:
         return make_response(redirect('/#!/?success=修改邮箱成功'))
Beispiel #6
0
def verify_timed_token(token):
    s = TimestampSigner(SECRET_KEY)
    try:
        data = s.loads(token)
    except (SignatureExpired, BadSignature):
        return None
    return data
Beispiel #7
0
def reset_user_password_step_two(form):
    """
    second step of the password reset: check that the hash matches the temp password, force the change on ads classic
    """
    #create an itsdangerous object to sign the verification email and encrypt the password
    itsd = TimestampSigner(config.ACCOUNT_VERIFICATION_SECRET)
    reset_code = form.resetcode.data
    try:
        code = itsd.unsign(reset_code, max_age=10800) #code valid only 3 hours
    except BadTimeSignature:
        app.logger.error('User password reset error: used reset code not valid. Email used: %s ; reset code: %s' % (form.login.data, reset_code))
        return False, 'The reset code is not valid.', 'error'
    except SignatureExpired:
        app.logger.error('User password reset error: used reset code expired. Email used: %s ; reset code: %s' % (form.login.data, reset_code))
        return False, 'The reset code has expired. Please request a new one.', 'error'
    
    #check if the reset code is the same stored in the DB
    loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.username==form.login.data) #@UndefinedVariable
    #get the user object
    user_rec = loc_db_user.first()
    if reset_code != user_rec.password:
        app.logger.error('User password reset error: used valid reset code but it doesn\'t match the one in the DB. Email used: %s ; reset code: %s' % (form.login.data, reset_code))
        return False, 'The reset code is not valid.', 'error'
    else:
        #proceed with the actual reset
        classic_user = reset_classic_password(form.login.data, form.new_password.data)
        if classic_user and classic_user.get('message') == 'ACCOUNT_UPDATED':
            #remove the reset code from the password field of the local db
            loc_db_user.set(password='').execute()
            return True, 'Password successfully updated.', 'success'
        else:
            app.logger.error('ADS Classic account modification error: return message not expected. Tried to force update password: login %s' % form.login.data)
            return False, 'Problems in the account modification. Please try again.', 'error'
Beispiel #8
0
def confirm_account(token):
    email = _check_token(token).decode('utf8')
    form = forms.SetPasswordForm()
    user = models.InviteApplicant.objects.filter(email=email).first()
    if not email:
        current_app.logger.info('token has expired.')
        flash('Link has expired', 'error')
    else:
        if user.password_set:
            flash('Account already confirmed and password set')
            return render_template('done.html', message='Account already confirmed and password set')

    if form.validate_on_submit():
        password = form.password.data
        www_id = app.config['WWW_CLIENT_ID']
        www_key = app.config['WWW_CLIENT_KEY']
        to_sign = '%s:%s:%s' % (www_id, email, password)
        signer = TimestampSigner(www_key, digest_method=hashlib.sha256)
        signed = signer.sign(to_sign)
        headers = { 'Authorisation': signed }
        url = '%s/update-user-password' % app.config['REGISTRY_BASE_URL']
        resp = requests.post(url, data={'email': email}, headers=headers)
        if resp.status_code == 200:
            user = models.InviteApplicant.objects.filter(email=email).first()
            user.password_set = True
            user.save()
            flash('Your password has been updated')
            return render_template('done.html', message='Your password has been updated')
        else:
            flash('Failed to set new password in registry', 'error')

    return render_template('set_account_password.html', form=form, token=token, user=user)
Beispiel #9
0
def make_server_request(request, payload, endpoint, auth=None, method="post"):
    """
    makes a json request to channelstream server endpoint signing the request and sending the payload
    :param request:
    :param payload:
    :param endpoint:
    :param auth:
    :return:
    """
    server_port = request.registry.settings["port"]
    signer = TimestampSigner(request.registry.settings["secret"])
    sig_for_server = signer.sign("channelstream")
    if not six.PY2:
        sig_for_server = sig_for_server.decode("utf8")
    secret_headers = {
        "x-channelstream-secret": sig_for_server,
        "Content-Type": "application/json",
    }
    url = "http://127.0.0.1:%s%s" % (server_port, endpoint)
    response = getattr(requests, method)(
        url, data=json.dumps(payload), headers=secret_headers, auth=auth
    )
    if response.status_code >= 400:
        log.error(response.text)
    response.raise_for_status()
    return response
Beispiel #10
0
class Tokenizer(object):
    """
    A class for creating cryptographically signed tokens used by CivID.

    >>> tokenizer = Tokenizer('123')
    >>> lt = tokenizer.create_login_token('gatzy')
    >>> tokenizer.validate_login_token(lt)
    'gatzy'
    >>> ic = tokenizer.create_identity_code('ttk2')
    >>> tokenizer.validate_identity_code(ic)
    'ttk2'
    """
    def __init__(self, signing_key):
        self.key = signing_key
        self.signer = TimestampSigner(signing_key)

    def short_sig(self, string):
        """
        Returns a token computed from truncating the hash of the given
        string with the signing key.
        """
        return base64.urlsafe_b64encode(
            hashlib.sha256(self.key + string).digest()
        )[:SHORT_SIG_LENGTH]

    def create_login_token(self, username):
        """
        Creates a login token of the form "signatureUsername".
        This token is bound to a UNIX timestamp divided by LOGIN_WINDOW_S,
        but it is not stored within the token in order to limit its length.
        """
        return self.short_sig(username + now_str()) + username

    def validate_login_token(self, token):
        if len(token) < SHORT_SIG_LENGTH + MIN_USERNAME_LENGTH:
            raise InvalidTokenError("Malformed token")

        signature = token[0:SHORT_SIG_LENGTH]
        user = token[SHORT_SIG_LENGTH:]
        
        if (
            signature != self.short_sig(user + now_str()) and 
            signature != self.short_sig(user + last_period_str())
        ):
            raise InvalidTokenError("Login link invalid or expired")

        return user

    def create_identity_code(self, username):
        # Identity codes contain this silly "scrambled" version of the username
        # to discourage naive implementations from parsing it out of the code
        # without making a request to validate it against the CivID server.
        return self.signer.sign(scramble_username(username))

    def validate_identity_code(self, code):
        try:
            return unscramble_username(self.signer.unsign(code, max_age=CODE_WINDOW_S))
        except:
            raise InvalidCodeError()
Beispiel #11
0
 def sign(self, session_id):
     """
     签名 session_id
     :param session_id:
     :return:
     """
     s = TimestampSigner(self._sign_key)
     return s.sign(session_id)
Beispiel #12
0
 def create_token(self):
     """
     生成 token (基于 uuid)
     """
     from uuid import uuid1
     from itsdangerous import TimestampSigner
     s = TimestampSigner(self._sign_key)
     return s.sign(str(uuid1()))
Beispiel #13
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
Beispiel #14
0
class TokenManager(object):
    def setup(self, secret):
        """ Create a cypher to encrypt IDs and a signer to sign tokens."""
        # Create cypher to encrypt IDs
        key = secret + '0123456789abcdef'  # ensure >=16 characters
        sixteen_byte_key = key[0:16]  # get first 16 characters
        self.cipher = AES.new(sixteen_byte_key)

        # Create signer to sign tokens
        self.signer = TimestampSigner(secret)

    def encrypt_id(self, id):
        """ Encrypts integer ID to url-safe base64 string."""
        str1 = '%016d' % id                             # --> 16 byte integer string
        str2 = self.cipher.encrypt(str1)                # --> encrypted data
        str3 = base64.urlsafe_b64encode(str2)           # --> URL safe base64 string with '=='
        return str3[0:-2]                               # --> base64 string without '=='

    def decrypt_id(self, encrypted_id):
        """ Decrypts url-safe base64 string to integer ID"""
        # In Python3, encrypted_id is <type 'str'> and needs to be converted to bytes
        if type(encrypted_id)=='str':   # pragma: no cover
            encrypted_id = encrypted_id.encode('ascii')

        try:
            str3 = encrypted_id + b'=='             # --> base64 string with '=='
            str2 = base64.urlsafe_b64decode(str3)   # --> encrypted data
            str1 = self.cipher.decrypt(str2)        # --> 16 byte integer string
            return int(str1)                        # --> integer id
        except Exception as e:                      # pragma: no cover
            print('!!!Exception in decrypt_id!!!')
            return 0

    def generate_token(self, id):
        """ Return token with id, timestamp and signature"""
        # In Python3 we must make sure that bytes are converted to strings.
        # Hence the addition of '.decode()'
        return self.signer.sign(self.encrypt_id(id)).decode()

    def verify_token(self, token, expiration_in_seconds):
        """ Verify token and return (is_valid, has_expired, id).
            Returns (True, False, id) on success.
            Returns (False, True, None) on expired tokens.
            Returns (False, False, None) on invalid tokens."""
        try:
            data = self.signer.unsign(token, max_age=expiration_in_seconds)
            is_valid = True
            has_expired = False
            id = self.decrypt_id(data)
        except SignatureExpired:
            is_valid = False
            has_expired = True
            id = None
        except BadSignature:
            is_valid = False
            has_expired = False
            id = None
        return (is_valid, has_expired, id)
Beispiel #15
0
def _check_token(token):
    from itsdangerous import TimestampSigner, SignatureExpired
    signer = TimestampSigner(app.config['SECRET_KEY'])
    try:
        email = signer.unsign(token, max_age=app.config['TOKEN_MAX_AGE_SECONDS'])
        return email
    except SignatureExpired as e:
        current_app.logger.info('token expired %s' % e)
        return None
Beispiel #16
0
def email_sign():
    """
    邮箱签名(带过期时间)
    http://localhost:5000/email/[email protected]
    """
    email = request.args.get('email', '')
    from itsdangerous import TimestampSigner
    s = TimestampSigner(app.config['SECRET_KEY'])
    return s.sign(email)
Beispiel #17
0
def load_user_from_request(request):
    authorization = request.headers.get('Authorization')
    if authorization is None or not authorization.startswith('Bearer '):
        return None
    token = authorization.split(' ', 1)[-1]
    signer = TimestampSigner(app.secret_key)
    id = signer.unsign(token)
    user = User.query.get(int(id))
    return user
Beispiel #18
0
def setup_password_reset(email):
    if email and urlfinder.get_userinfo(email):
        s = TimestampSigner(settings["secret_key"])
        signed_string_b64 = base64.b64encode(s.sign(email))

        msg = Message(body="Hi,\nYou requested a password reset.\nHere is your reset link: " + settings["domain"] + "?token=" + signed_string_b64 + "#reset",
                        subject="Password reset",
                        recipients=[email])
        mail.send(msg)
def decrypt(string, max_age=15000):
    """
    This method will return decrypted version of an encrypted string.
    If age of encryption is greater than max age it will return False
    """
    try:
        signer = TimestampSigner(encrypt_key)
        return signer.unsign(string, max_age=max_age)
    except:
        return False
def encrypt(string):
    """
    This method will return encrypted version of a string.
    It will return False if encryption fails
    """
    try:
        signer = TimestampSigner(encrypt_key)
        return signer.sign(string)
    except:
        return False
Beispiel #21
0
	def verify_auth_token(token):
		s = TimestampSigner(current_app.config['SECRET_KEY'])
		try:
			id = s.unsign(token, max_age=3600)
		except SignatureExpired:
			return None # valid token, but expired
		except BadSignature:
			return None # invalid token

		user = User.query.get(id)
		return user
Beispiel #22
0
def validate_reset_token(reset_user, token):
	s = TimestampSigner(app.config.get('SECRET_KEY'))
	try:
		new_token = s.unsign(token, max_age=43200)
		redis_val = app.redis_db.get("password-reset:#"+str(reset_user))
		if (token == redis_val.decode("utf8")):
			return True
		else:
			return False
	except Exception as e:
		return False
Beispiel #23
0
class Auth:

    @classmethod
    def __init__(self, app):
        self.signer = TimestampSigner(app.config['SECRET_KEY'])
        self.app = app

    @classmethod
    def requires_login(self, f):
        @wraps(f)
        def decorated(*args, **kwargs):
            authentication_token = request.headers.get('Authentication-Token')

            if not authentication_token or not self.__is_token_valid(
                    authentication_token):
                return response(
                    status=401,
                    message='Not authorized'
                )

            return f(*args, **kwargs)

        return decorated

    @staticmethod
    def hash_password(password):
        return hashlib.sha256(password).hexdigest()

    @classmethod
    def generate_auth_token(self):
        token_random_string = ''.join(
            choice(ascii_letters) for i in range(
                self.app.config['TOKEN_RANDOM_STRING_LENGTH']))

        return self.signer.sign(token_random_string)

    @classmethod
    def __is_token_valid(self, authentication_token):
        try:
            self.signer.unsign(
                authentication_token,
                max_age=self.app.config['TOKEN_VALIDITY_DURATION']
            )

        except SignatureExpired as e:
            self.app.logger.info('INFO: SignatureExpired, %s', str(e))
            return False    # valid token, but expired
        except BadSignature as e:
            self.app.logger.info('INFO: BadSignature, %s', str(e))
            return False    # invalid token

        return True
Beispiel #24
0
    def dispatch(self, *args, **kwargs):
        if "em_tk" not in self.request.GET:
            return HttpResponseRedirect(reverse('home'))

        email_token =  self.request.GET.get('em_tk')
        s = TimestampSigner(SECRET_KEY,salt="change-password")
        try:
            self.email_address = s.unsign(email_token, max_age=MAX_TOKEN_AGE)
        except:# itsdangerous.BadSignature:
            raise Http404
            #return HttpResponseRedirect(reverse('home'))

        return super(PasswordChangeView, self).dispatch(*args, **kwargs)
Beispiel #25
0
def authorize(request):
	auth_header = request.headers.get('Authorization')
	if auth_header:
		try:
			auth_token = auth_header.split(" ")[1]
		except IndexError:
			responseObject = {
				'status': 'fail',
				'message': 'Bearer token malformed.',
				'status_int': 401
			}
			return make_response(jsonify(responseObject), 401)
	else:
		auth_token = ''
	if auth_token:
		resp = User.decode_auth_token(auth_token)
		if not isinstance(resp, str):
			s = TimestampSigner(app.config.get('SECRET_KEY'))
			try:
				csrf_token = s.unsign(request.headers.get('CSRF-Token'))
			except Exception as e:
				responseObject = {
					'status': 'fail',
					'message': 'Invalid data.',
					'status_int': 401
				}
				return make_response(jsonify(responseObject), 401)
			user = User.query.filter_by(id=resp).first()
			responseObject = {
				'status': 'success',
				'data': {
				'user_id': user.id,
				'email': user.email,
				'admin': user.admin,
				'registered_on': user.registered_on
				}
			}
			return make_response(jsonify(responseObject), 201)
		responseObject = {
			'status': 'fail',
			'message': resp,
			'status_int': 401
		}
		return make_response(jsonify(responseObject), 401)
	else:
		responseObject = {
			'status': 'fail',
			'message': 'Provide a valid auth token.',
			'status_int': 401
		}
		return make_response(jsonify(responseObject), 401)
def reset_password_from_token(reset_token, new_password):
    s = TimestampSigner(os.getenv("SECRET_KEY"), salt="reset-password")
    try:
        email = s.unsign(reset_token, max_age=60*60*24).lower()  # 24 hours

    except SignatureExpired:
        raise PasswordResetError("expired-token")

    except (BadTimeSignature, BadSignature):
        raise PasswordResetError("invalid-token")

    user = get_profile_from_id(email, "email", include_products=False)
    user.set_password(new_password)
    return user
Beispiel #27
0
def reset_user_password_step_one(form):
    """
    first step of the password reset: hash generated, email with hash sent
    """
    # create an itsdangerous object to sign the verification email and encrypt the password
    itsd = TimestampSigner(config.ACCOUNT_VERIFICATION_SECRET)
    # generate a temporary password
    temp_password = os.urandom(12).encode("hex")
    reset_code = itsd.sign(temp_password)
    time_limit = datetime.now() + timedelta(hours=3)
    # check local database
    loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.username == form.login.data)  # @UndefinedVariable
    # get the user object
    user_rec = loc_db_user.first()
    if not user_rec:
        app.logger.error("User password reset error: user not in db. Email used: %s" % form.login.data)
    else:
        # store the reset password locally
        loc_db_user.set(password=reset_code).execute()

        # sent the email
        message_html = """<h3>ADS Password reset</h3>
                                <p>Your temporary reset code is <strong>%(reset_code)s</strong></p>
                                <p>To complete the password reset, please click <a href="%(reset_url)s">here</a></p>
                                <p>If the link doesn't work, please copy the following URL and paste it in your browser:<br/>%(reset_url)s</p>
                                <p>This temporary reset code is valid only until %(password_time_limit)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>
                            """ % {
            "reset_code": reset_code,
            "reset_url": "%s%s?login=%s&resetcode=%s"
            % (
                config.MAIL_CONTENT_REDIRECT_BASE_URL,
                url_for("user.confirm_reset_password"),
                form.login.data,
                reset_code,
            ),
            "feedb_url": "%s%s" % (config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for("feedback.feedback")),
            "password_time_limit": time_limit.strftime("%A, %d. %B %Y %I:%M%p"),
        }
        try:
            send_email_to_user(u"NASA ADS: confirmation required for login update", message_html, [form.login.data])
        except:
            app.logger.error("Failed to send reset email for user password.")
            return False, "There are some technical problems: please try later.", "error"
    return (
        True,
        "If the email you entered exists in our system, you will shortly receive a message at your e-mail address with further instructions on how to reset your password.",
        "warning",
    )
Beispiel #28
0
    def send_email(self, host):
        # send email using the self.cleaned_data dictionary
        data = self.cleaned_data
        email = data['email']

        s = TimestampSigner(SECRET_KEY, salt="register-user")
        token_string = s.sign(email)
        registration_url = reverse('activate_user')
        registration_url += "?em_tk=" + token_string
        #registration_url = PRODUCTION_BASE_URL + registration_url
        registration_url = "http://" +  host + registration_url
        
        ctx = { 'email' : email, 'registration_url' : registration_url }
        send_template_email(_("Email verification for signup"), "verified_registration/registration_mail.html", ctx, email)
Beispiel #29
0
def reset_password(userid, user_email):
    s = TimestampSigner(app.secret_key)
    userid = s.sign(userid)
    token = s.sign(user_email)
    body = (
        "Hey, a password reset for this account was requested.  If you wish to continue, then please follow the link below:\n"
        + app.hvb_conf["domain"]
        + "/reset/"
        + userid
        + "/token/"
        + token
    )
    subject = "[HumanVoiceBankInitiative] Password Reset for " + user_email
    send_mail(subject, body, app.hvb_conf["admin_email"], user_email)
Beispiel #30
0
 def check_token(self, token_sign):
     """
     校验 token, 返回解密后的 token
     """
     from itsdangerous import TimestampSigner, SignatureExpired, BadTimeSignature
     s = TimestampSigner(self._sign_key)
     try:
         token = s.unsign(token_sign, max_age=60)  # 60秒过期
         return {'success': token}
     except SignatureExpired as e:
         # 处理签名超时
         return {'error': e.message}
     except BadTimeSignature as e:
         # 处理签名错误
         return {'error': e.message}
Beispiel #31
0
    """
    return getent info and snotsig
    """
    try:
        passwd = dict(getent.passwd(name))
    except TypeError:
        abort(400, "Invalid user")
    snotsig_path = '/home/{0}/solaris/.snotsig'.format(name)
    sig_path = '/home/{0}/solaris/.snotsig'.format(name)
    if os.path.isfile(snotsig_path):
        with open(snotsig_path) as f:
            snotsig = f.read()
        f.closed
    elif os.path.isfile(sig_path):
        with open(sig_path) as f:
            snotsig = f.read()
        f.closed
    #TODO check linux homedir as well
    else:
        snotsig = ""
    return jsonify({"passwd": passwd, "snotsig": snotsig})


if __name__ == "__main__":
    with open('config.yaml') as f:
        conf = yaml.load(f.read())
    f.closed
    s = TimestampSigner(conf['secret_key'])

    app.run(debug=True, port=conf['port'])
Beispiel #32
0
def generate_timed_token(user_dict, expiration=TOKEN_EXPIRES):
    s = TimestampSigner(SECRET_KEY, expires_in=expiration)
    return s.dumps(user_dict)
Beispiel #33
0
 def encode(self, email):
     s = TimestampSigner(config.SECRET_KEY)
     e = s.sign(email)
     s = URLSafeSerializer(config.SECRET_KEY)
     e = s.dumps(e)
     return e
Beispiel #34
0
class TokenManager(object):
    def setup(self, secret):
        """ Create a cypher to encrypt IDs and a signer to sign tokens."""
        # Create cypher to encrypt IDs
        # and ensure >=16 characters
        precursor = b'0123456789abcdef'
        if isinstance(secret, bytes):
            key = secret + precursor
        else:
            key = secret.encode("utf-8") + precursor
        self.cipher = AES.new(key[0:16], AES.MODE_ECB)

        # Create signer to sign tokens
        self.signer = TimestampSigner(secret)

    def encrypt_id(self, id):
        """ Encrypts integer ID to url-safe base64 string."""
        # 16 byte integer
        str1 = '%016d' % id
        # encrypted data
        str2 = self.cipher.encrypt(str1.encode())
        # URL safe base64 string with '=='
        str3 = base64.urlsafe_b64encode(str2)
        # return base64 string without '=='
        return str3[0:-2]

    def decrypt_id(self, encrypted_id):
        """ Decrypts url-safe base64 string to integer ID"""
        # Convert strings and unicode strings to bytes if needed
        if hasattr(encrypted_id, 'encode'):
            encrypted_id = encrypted_id.encode('ascii', 'ignore')

        try:
            str3 = encrypted_id + b'=='  # --> base64 string with '=='
            str2 = base64.urlsafe_b64decode(str3)  # --> encrypted data
            str1 = self.cipher.decrypt(str2)  # --> 16 byte integer string
            return int(str1)  # --> integer id
        except Exception as e:  # pragma: no cover
            print('!!!Exception in decrypt_id!!!:', e)
            return 0

    def generate_token(self, id):
        """ Return token with id, timestamp and signature"""
        # In Python3 we must make sure that bytes are converted to strings.
        # Hence the addition of '.decode()'
        return self.signer.sign(self.encrypt_id(id)).decode()

    def verify_token(self, token, expiration_in_seconds):
        """ Verify token and return (is_valid, has_expired, id).
            Returns (True, False, id) on success.
            Returns (False, True, None) on expired tokens.
            Returns (False, False, None) on invalid tokens."""
        try:
            data = self.signer.unsign(token, max_age=expiration_in_seconds)
            is_valid = True
            has_expired = False
            id = self.decrypt_id(data)
        except SignatureExpired:
            is_valid = False
            has_expired = True
            id = None
        except BadSignature:
            is_valid = False
            has_expired = False
            id = None
        return (is_valid, has_expired, id)
Beispiel #35
0
 def get_signer(self):
     """Return signer for cookie content signing."""
     return TimestampSigner(secret_key, self.sign_salt)
    return app


# Sqlalchemy
db = SQLAlchemy()
app = create_app("sqlite:///./dbdir/ohlife.db", True)
# flask-jwt
jwt = JWT(app, authenticate, identity)
# flask-admin
admin = Admin(app, name='ohlife', template_mode='bootstrap3')
# flask-login
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# itsdangerous
url_serializer = URLSafeSerializer(app.config["SECRET_KEY"])
save_signer = TimestampSigner(app.config["SECRET_KEY"], salt="save")
unsub_signer = TimestampSigner(app.config["SECRET_KEY"], salt="unsub")
# flask-limiter
limiter = Limiter(
    app,
    key_func=get_remote_address,
    default_limits=["30 per minute", "10 per second"]
)

# logging
handler = RotatingFileHandler('foo.log', maxBytes=100000, backupCount=3)
handler.setLevel(logging.ERROR)
# sentry error handler
# client = Client('')
# handler = SentryHandler(client)
# handler.setLevel(logging.ERROR)
Beispiel #37
0
def make_auth_token(auth_user):
    """Generates an authentication token for the given user."""
    signer = TimestampSigner(current_app.secret_key)
    return signer.sign(str(auth_user.uid)).decode()
Beispiel #38
0
def generate_agent_websocket_token(agent):
    signer = TimestampSigner(app.config['SECRET_KEY'], salt="websocket_agent")
    assert agent.id is not None
    token = signer.sign(str(agent.id))
    return token
Beispiel #39
0
)
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.extensions import limiter
from app.log import LOG
from app.models import (
    Alias,
    CustomDomain,
    DeletedAlias,
    Mailbox,
    User,
    AliasMailbox,
    DomainDeletedAlias,
)

signer = TimestampSigner(CUSTOM_ALIAS_SECRET)


@dataclass
class SuffixInfo:
    """
    Alias suffix info
    WARNING: should use AliasSuffix instead
    """

    # whether this is a custom domain
    is_custom: bool
    suffix: str
    signed_suffix: str

    # whether this is a premium SL domain. Not apply to custom domain
Beispiel #40
0
 def create(self, user_id):
     s = TimestampSigner(current_app.config.SECRET_KEY)
     return s.sign({"datetime": datetime.now(), "user_id": user_id})
Beispiel #41
0
 def __init__(self, secret, store, cookie='sid'):
     self.store = store
     self.delta = store.delta  # lifespan delta in seconds.
     self.cookie_name = cookie
     self.signer = TimestampSigner(secret)
def validate_email(email):
    if len(email) > 7:
        if re.match(
                "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$",
                email) != None:
            return True
    return False


if __name__ == "__main__":
    sender_email = input("Type your email address and press enter: ")
    password = getpass.getpass(prompt="Type your password and press enter:")
    receiver_email = input("Type reciever's email address and press enter: ")
    if validate_email(sender_email) and validate_email(receiver_email):
        s = TimestampSigner(SECRET_KEY)
        otp = temp_otp()
        message = f"""\nThis message is sent from Python for Email Id Verification, by prateek-manocha.\n\
The OTP is {s.unsign(otp).decode()}"""
        send_email(sender_email, password, receiver_email, message)
        print("Verification email sent succesfully.")
        try:
            while True:
                otp = s.unsign(otp, max_age=50).decode()
                otp_entered = input("Enter the OTP received(case sensetive): ")
                if otp_entered == otp:
                    print("Email Verified.")
                    break
                else:
                    print("Wrong OTP entered.")
        except:
Beispiel #43
0
from itsdangerous import Signer, BadSignature

s = Signer("secret-key")
signed_text = s.sign("test string")
print(s.unsign(signed_text))

try:
    s.unsign(b"different string.wh6tMHxLgJqB6oY1uT73iMlyrOA")
except BadSignature:
    print("Signature does not match")


from itsdangerous import TimestampSigner, SignatureExpired
import time

s = TimestampSigner('secret-key')
signed_text = s.sign('text')
time.sleep(2)
try:
    print(s.unsign(signed_text, max_age=1))
except SignatureExpired:
    print("SignatureExpired")
Beispiel #44
0
def data_download(event):
    download_url.text = ''
    output_format = 'csv'
    rv = base64.b64encode(uuid.uuid4().bytes).decode('utf-8')
    unique = re.sub(r'[\=\+\/]', lambda m: {
        '+': '-',
        '/': '_',
        '=': ''
    }[m.group(0)], rv)
    filename = str(unique) + '.' + str(output_format)
    s = TimestampSigner('secret-key')
    download_token = s.sign(filename).decode()
    # dirpath = os.path.join(os.path.dirname(__file__),'static', download)
    dirpath = os.environ['TSPLOT_DOWNLOAD']
    outfile = Path(dirpath, str(download_token))
    if data.feature_type in ['TimeSeriesProfile', 'Profile']:
        index_range = np.array([p.y_range.end, p.y_range.start]).tolist()
    else:
        index_range = np.array([p.x_range.start, p.x_range.end],
                               dtype='i8').view('datetime64[ms]').tolist()

    start = df.index.searchsorted(index_range[0])
    end = df.index.searchsorted(index_range[1])
    # TODO: check for the output format [netcdf / csv]
    if export_resampling.active and resampling.value != '--':
        df_export = df[[
            variables[x] for x in export_variables.active
        ]][df.index[start]:df.index[end - 1]].resample(
            resampling.value).mean().interpolate(method='linear')
    else:
        df_export = df[[variables[x] for x in export_variables.active
                        ]][df.index[start]:df.index[end - 1]]
    if export_format.value == 'csv':
        outfile = Path(dirpath, str(download_token)).with_suffix('.zip')
        compression_opts = dict(method='zip',
                                archive_name=f'{select.value}.csv')
        #df[select.value][df.index[start]:df.index[end-1]].to_csv(outfile, header=True)
        #
        ### df[select.value][df.index[start]:df.index[end-1]].to_csv(outfile, compression=compression_opts, header=True)
        df_export.to_csv(outfile, compression=compression_opts, header=True)
        # zip_resource = zipfile.ZipFile(outfile, 'a')
        # shall we add a figure?
        # zip.write('metadata.html', os.path.basename('metadata.html'))
        # zip_resource.close()
    else:
        outfile = Path(dirpath, str(download_token)).with_suffix('.nc')
        xr = xarray.Dataset.from_dataframe(df_export)
        # TODO: add attributes and metadata, probably worth to do some reindexing
        xr.to_netcdf(outfile)
    #
    # url_text=f'<a href="http://localhost:5100/test/TS-Plot/static/Download/{download_token}">Variable: {select.value}, from: {df.index[start]} to: {df.index[end-1]}</a>'
    try:
        server_domain = os.environ['ORIGIN']
        prefix = os.environ['PREFIX']
    except KeyError:
        server_domain = 'localhost:5100'
        prefix = 'test'
    url_text = ''
    url_text = f'<a href="http://{server_domain}/{prefix}/TS-Plot/static/Download/{outfile.name}">Selected data </a> <font size = "2" color = "darkslategray" > <br> <br> <b>selected index:</b> <br> [{df.index[start]}, {df.index[end-1]}] <br> <br> <b>selected variables:</b> <br> {[variables[x] for x in export_variables.active]}</font>'
    if data.feature_type == 'TimeSeries':
        url_text += f"""<br> <font size = "2" color = "darkslategray" ><b>Frequency:</b> <br>{resampling.value} </font>"""
    if data.feature_type == 'TimeSeriesProfile':
        date_time = get_datetime_string(list(data.keys())[int(slider.value)])
        url_text += f"""<br> <font size = "2" color = "darkslategray" >selected profile: # {slider.value} {date_time}</font>"""
    url_text += f"""<br><br> <a href="{str(args.get('url')[0].decode())}.html" target="_blank">RAW data</a>"""
    download_url.text = url_text
Beispiel #45
0
 def __init__(self) -> None:
     self.serializer = TimestampSigner(current_app.config.SECRET_KEY)
Beispiel #46
0
def gen_signature(secret):
    from itsdangerous import TimestampSigner

    signer = TimestampSigner(secret)
    return signer.sign("channelstream")
Beispiel #47
0
def gen_signup_token(username):
    return TimestampSigner(current_app.secret_key).sign(username.encode("utf-8")).decode("utf-8")
Beispiel #48
0
 def post(self, workspace_name):
     workspace = self._get_workspace(workspace_name)
     signer = TimestampSigner(app.config['SECRET_KEY'], salt="websocket")
     token = signer.sign(str(workspace.id)).decode('utf-8')
     return {"token": token}
Beispiel #49
0
 def _get_signer(self):
     if self._signer is None:
         # We are using the timestampsigner because we want to be always
         #  needing to think about expiry of the signatures
         self._signer = TimestampSigner(APP.config['GLOBAL']['secret_key'])
     return self._signer
Beispiel #50
0
def password_reset_token(user):
    signer = TimestampSigner(fame_config.secret_key)

    return signer.sign(str(user['_id']))
Beispiel #51
0
from itsdangerous import TimestampSigner

# Create the application
APP = flask.Flask(__name__)

APP.config.from_envvar('FEDOAUTH_CONFIG')

# Make sure the configuration is sane
if APP.config['GLOBAL']['url_root'].endswith('/'):
    print 'Error: Make sure url_root does NOT end with a trailing slash'
    sys.exit(1)
if APP.config['GLOBAL']['secret_key'] == 'setme':
    print 'Error: Please configure a secret key'
    sys.exit(1)

signer = TimestampSigner(APP.config['GLOBAL']['secret_key'])

logging.config.fileConfig(APP.config['GLOBAL']['logging_config_location'])

logger = logging.getLogger(__name__)

# Set up SQLAlchemy
# DEPRECATED: the global SQLALCHEMY_DATABASE_URI is deprecated, but should stay supported during the 3.0.X series
db_url = None
db_debug = APP.config['GLOBAL'].get('database_debug', False)
db_url = APP.config['GLOBAL']['database_url']
dbengine = create_engine(db_url, echo=db_debug, pool_recycle=3600)
dbsession = scoped_session(sessionmaker(bind=dbengine))

import fedoauth.utils as utils
if APP.config['GLOBAL']['reverse_proxied']:
Beispiel #52
0
def validate_password_reset_token(token):
    signer = TimestampSigner(fame_config.secret_key)

    return signer.unsign(token, max_age=86400).decode()
Beispiel #53
0
async def download(
    *,
    resource_url: str = Query(...,
                              title="Resource URL",
                              description="URL to a NetCDF resource"),
    variable: List[str] = Query(None,
                                title="Variable name",
                                description="List of NetCDF Variable names"),
    output_format: str = Query(None,
                               title="output format",
                               description="output format",
                               regex='^(csv|nc)$')):
    # list of variables
    plottable_variables = get_variables(resource_url)
    axis = list(plottable_variables.keys())[0]
    if not variable:
        variables_items = {'variables': plottable_variables[axis]}
    else:
        variables_items = {'variables': variable}
    # check if the user provided valid parameters
    valid_vars = []
    for i in variables_items['variables']:
        if i in plottable_variables[axis]:
            valid_vars.append(i)
        else:
            print('removed:', i)
    print(valid_vars)
    # create an empty list to append one dataframe for each variables
    data = []
    for i in valid_vars:
        # get_data is handling only variable selection at the moment
        # TODO: add an option in get_data to allow time-selection
        #  a good candidate for this is by using pandas time-range slicing
        #  it will require one extra parameters in the URL request,
        #  to handle start/end time selection
        data.append(get_data(resource_url, i))
    # merge the requested data in a single dataframe
    # suffixes = ['_'+i.variable_metadata['standard_name'] for i in data]
    try:
        df_final = reduce(
            lambda left, right: pd.merge(
                left, right, suffixes=(False, False), on=data[0].index.name),
            data)
    except ValueError:
        suffixes = ['_' + i.variable_metadata['standard_name'] for i in data]
        df_final = reduce(
            lambda left, right: pd.merge(
                left, right, suffixes=suffixes, on=data[0].index.name), data)
    # generate a uuid for the filename
    if not output_format:
        output_format = 'csv'
    if output_format == 'csv':
        rv = base64.b64encode(uuid.uuid4().bytes).decode('utf-8')
        unique = re.sub(r'[\=\+\/]', lambda m: {
            '+': '-',
            '/': '_',
            '=': ''
        }[m.group(0)], rv)
        filename = str(unique) + '.' + str(output_format) + '.zip'
        # TODO: read the secret-key from a configuration file
        s = TimestampSigner('secret-key')
        download_token = s.sign(filename).decode()
        # this stores the data in the 'DOWNLOAD_DIR' which is set in the docker-compose.yml instruction
        outfile = Path(os.environ['DOWNLOAD_DIR'], str(filename))
        compression_opts = dict(method='zip', archive_name='dataset' + '.csv')
        df_final.to_csv(outfile, compression=compression_opts)
        with open('metadata.csv', 'w', newline="") as csv_file:
            writer = csv.writer(csv_file)
            for key, value in data[0].dataset_metadata.items():
                writer.writerow([key, value])
        with open('metadata.html', 'w') as f:
            f.write(
                json2html.convert(json={**data[0].dataset_metadata},
                                  table_attributes="id=\"metadata\" "))
        zip = zipfile.ZipFile(outfile, 'a')
        zip.write('metadata.html', os.path.basename('metadata.html'))
        zip.write('metadata.csv', os.path.basename('metadata.csv'))
        zip.close()
        # the line below will return a direct download
        # if os.path.isfile(outfile):
        #     return FileResponse(path=outfile, filename='dataset.csv.zip')
        return RedirectResponse(url='/download/%s' % str(download_token))
    if output_format == 'nc':
        filename = str(uuid.uuid5(uuid.NAMESPACE_URL,
                                  'download')) + '.' + str(output_format)
        s = TimestampSigner('secret-key')
        download_token = s.sign(filename).decode()
        # this stores the data in the 'DOWNLOAD_DIR' which is set in the docker-compose.yml instruction
        outfile = Path(os.environ['DOWNLOAD_DIR'], str(filename))
        ds = df_final.to_xarray()
        ds.attrs = data[0].dataset_metadata
        for i in data:
            ds[i.columns.values[0]].attrs = i.variable_metadata
        ds.to_netcdf(outfile)
        return RedirectResponse(url='/download/%s' % str(download_token))
Beispiel #54
0
 def generate_validate_token(self, username):
     serializer = utsr(self.security_key)
     timeStamp = TimestampSigner(self.security_key)
     username = timeStamp.sign(username)
     return serializer.dumps(username, self.salt)
Beispiel #55
0
 def remove_validate_token(self, token):
     serializer = utsr(self.security_key)
     timeStamp = TimestampSigner(self.security_key)
     username = serializer.loads(token, salt=self.salt)
     username = timeStamp.unsign(username)
     return username
def generate_token(email, app):
    signer = TimestampSigner(app.config["SECRET_KEY"])
    return signer.sign(email).decode("utf8")
Beispiel #57
0
from boto.exception import S3CreateError, S3ResponseError
from selenium import webdriver
import sendgrid
from flask import render_template
from itsdangerous import TimestampSigner, SignatureExpired

from exam_app import app
from exam_app.models.past_exam_results import PastExamResult
from exam_app.models.attempted_mock_test import AttemptedMockTest
from exam_app.models import db
from exam_app.exceptions import InvalidAttemptedMockTestId
from exam_app.models.mock_test import MockTest
from exam_app.models.student import Student

#SendGridClient = sendgrid.SendGridClient(app.config['SENDGRID_USER'], app.config['SENDGRID_KEY'])
TIMESTAMP_SIGNER = TimestampSigner(app.config['SECRET_KEY'])


class S3(object):
    def __init__(self, key=None, secret=None):
        if key and secret:
            self.access_key = key
            self.secret = secret
        else:
            self.access_key = app.config['S3_ACCESS_KEY']
            self.secret = app.config['S3_SECRET']
        self.connection = S3Connection(self.access_key, self.secret)
        self.create_bucket = self.connection.create_bucket
        self.get_bucket = self.connection.get_bucket

    @staticmethod
Beispiel #58
0
from itsdangerous import TimestampSigner, BadSignature

parser = argparse.ArgumentParser()
parser.add_argument('--host', default='127.0.0.1')
parser.add_argument('--port', default=8888, type=int)
parser.add_argument('key')
parser.add_argument('target_dir')
parser.add_argument('rsync_host')
args = parser.parse_args()


logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)


signer = TimestampSigner(args.key)


async def run_cmd(cmd):
    proc = await asyncio.create_subprocess_shell(
        cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)

    stdout, stderr = await proc.communicate()

    if stdout:
        print(f'[stdout]\n{stdout.decode()}')
    if stderr:
        print(f'[stderr]\n{stderr.decode()}')
async def test_start_and_register(
    register_options,
    test_config: FaradayTestConfig,  # noqa F811
    tmp_default_config,  # noqa F811
    test_logger_handler,  # noqa F811
):
    os.environ["DISPATCHER_TEST"] = "True"
    if "use_ssl" in register_options:
        if (register_options["use_ssl"] and not test_config.is_ssl) or (
            not register_options["use_ssl"] and test_config.is_ssl
        ):
            pytest.skip(
                f"This test should be skipped: server_ssl:{test_config.is_ssl}"
                f" and config_use_ssl:f {register_options['use_ssl']}"
            )

    client = test_config.client

    if test_config.base_route:
        configuration.set(Sections.SERVER, "base_route", test_config.base_route)

    # Config
    configuration.set(Sections.SERVER, "ssl", str(test_config.is_ssl))
    if test_config.is_ssl:
        configuration.set(Sections.SERVER, "ssl_cert", str(test_config.ssl_cert_path / "ok.crt"))
        configuration.set(Sections.SERVER, "host", "localhost")
    else:
        configuration.set(Sections.SERVER, "host", client.host)

    configuration.set(Sections.SERVER, "api_port", str(client.port))
    configuration.set(Sections.SERVER, "workspaces", test_config.workspaces_str())
    configuration.set(Sections.TOKENS, "registration", test_config.registration_token)
    configuration.set(Sections.EXECUTOR_DATA.format("ex1"), "cmd", "exit 1")

    for section in register_options["replace_data"]:
        for option in register_options["replace_data"][section]:
            if section not in configuration:
                configuration.add_section(section)
            configuration.set(section, option, register_options["replace_data"][section][option])

    tmp_default_config.save()

    # Init and register it
    dispatcher = Dispatcher(client.session, tmp_default_config.config_file_path)

    if "expected_exception" not in register_options:
        await dispatcher.register()
        # Control tokens
        assert dispatcher.agent_token == test_config.agent_token

        signer = TimestampSigner(test_config.app_config["SECRET_KEY"], salt="websocket_agent")
        agent_id = int(signer.unsign(dispatcher.websocket_token).decode("utf-8"))
        assert test_config.agent_id == agent_id
    else:
        with pytest.raises(register_options["expected_exception"]):
            await dispatcher.register()

    history = test_logger_handler.history

    logs_ok, failed_logs = await check_logs(history, register_options["logs"])

    if "optional_logs" in register_options and not logs_ok:
        logs_ok, new_failed_logs = await check_logs(history, register_options["optional_logs"])
        failed_logs = {"logs": failed_logs, "optional_logs": new_failed_logs}

    assert logs_ok, failed_logs
Beispiel #60
0
from flask import abort, g
from flask_restful import Resource, reqparse
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimestampSigner, SignatureExpired, BadSignature
from dateutil import parser
from .utils import check_datetime
from .config import config
from .database import db
from .modules import User, Section, Post, Comment, BlockItem


auth = HTTPTokenAuth(scheme='Token')
signer = TimestampSigner(config['SECRET_KEY'])


@auth.verify_token
def verify_token(token):
    try:
        user_id = signer.unsign(token, max_age=config['MAX_AGE']).decode()
    except SignatureExpired:
        return False
        # abort(403, "Signature Expired")
    except BadSignature:
        return False
        # abort(403, "Signature not match")
    g.user = User.query.filter_by(user_id=user_id).first()
    if g.user is None:
        return False
    return True