Beispiel #1
0
def ResetPassword(request, token):
    restdata = {'data': '', 'regerror': '', 'token': token}
    registerobj = forms.Register()
    restdata['data'] = registerobj
    if request.method == 'POST':
        s = TimestampSigner(django_settings.SECRET_KEY)
        email = s.unsign(token)

        form = forms.ResetPassword(request.POST)
        if form.is_valid():
            password1 = request.POST['password1']
            password2 = request.POST['password2']
            if form.pwd_validate(password1, password2):
                try:
                    s = TimestampSigner(django_settings.SECRET_KEY)
                    s.unsign(token, max_age=300)
                except:
                    msg = {'msgerror': u'哎哟我去,连接已过期,请重发邮件!!'}
                    return HttpResponse(json.dumps(msg))
                users = Suser.objects.get(email=email)
                users.set_password(password1)
                users.save()
                msg = {'msginfo': u'恭喜您,密码修改成功!!!'}
                return HttpResponse(json.dumps(msg))
            else:
                msg = {'msgerror': u'密码输入不一致!!'}
                return HttpResponse(msg)
        else:
            restdata['data'] = form
    else:
        return render(request, 'webapp/resetpass.html', restdata)
Beispiel #2
0
def signup():
    if request.method == "POST":
        error = None
        token = request.form['token']
        ts = TimestampSigner(current_app.secret_key)
        try:
            username = ts.unsign(token, 60*5).decode("utf-8") # 2 minutes
        except SignatureExpired:
            error = "Token has expired"
        except BadSignature:
            error = "Invalid token"
        else:
            db = get_db()
            users = db.table("users")
            if users.contains(Query().username == username):
                error = "That user already exists"
            else:
                users.insert({"username":username,"role":0,"password":generate_password_hash(request.form['password'])})
        if error is None:
            session.clear()
            flash("Successfully created user! You can now login.", "success")
            return redirect(url_for("auth.login"))
        else:
            flash(error, "error")
    return render_template("auth/signup.html")
Beispiel #3
0
    def _sign_cookie(self, cookie: dict, signing_key: str) -> str:
        """
        Sign and encode a cookie ready for transport and secure comms with trusted services
        Use ``self.sign_cookie`` for public use
        :param cookie: dict of data to sign
        :param signing_key: key to sign data with
        :return: str signed cookie payload
        """
        self._logger.info(f"Starting to sign cookie: {cookie}")
        encoded_payload = json.dumps(cookie)

        try:
            result: str = (
                TimestampSigner(secret_key=signing_key)
                .sign(encoded_payload)
                .decode("utf8")
            )
        except Exception as e:
            self._logger.error(
                f"Unexpected problem signing cookie payload: {cookie}: {e}"
            )
            raise self._exceptions.ServiceUnavailable

        self._logger.info(f"Finished signing cookie: {cookie}")
        return result
Beispiel #4
0
 def test_general_api_security(self):
     ##TODO: Add General API security test
     """This Tests the API security that is checked before all POST and GET request"""
     get_return = self.app.get('/api/client_view',
                               headers={
                                   'API_KEY': 'api_key',
                                   'Client_ID': 'testuser'
                               })
     assert 'Failure": "Incorrect API Key' in get_return.data
     api_key = self.post_info()
     get_return = self.app.get('/api/client_view',
                               headers={
                                   'API_KEY': api_key[0],
                                   'Client_ID': 'fakeuser'
                               })
     assert 'Failure": "Invaild User' in get_return.data
     user = User.query.filter_by(Client_id="testuser2").first()
     get_return = self.app.get('/api/client_view',
                               headers={
                                   'API_KEY': user.api_key,
                                   'Client_ID': 'testuser2'
                               })
     assert 'Failure": "Incorrect IP for Client, Please Re-login in' in get_return.data
     signer = TimestampSigner(SECRET_KEY)
     time.sleep(1)
     try:
         signer.unsign(api_key, max_age=1)
         raise
     except:
         pass
Beispiel #5
0
def reset():
    pass_secret = current_app.config.get('PASS_SECRET_KEY')
    pass_token_age = current_app.config.get('PASS_TOKEN_AGE')
    test_mode = current_app.config.get('TESTING')

    token = request.json.get('token')
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    singer = TimestampSigner(pass_secret)

    try:
        email_bytes = singer.unsign(token.encode(), max_age=pass_token_age)
        email = email_bytes.decode('utf-8')
        user = User.get_by_email(email)

        if user and user.password_match(old_password):
            user.update(password=new_password)

            return make_response(jsonify({'message': 'Password resetted!'}),
                                 HTTPStatus.CREATED)

        return make_response(jsonify({'message': {
            'email': 'Not found'
        }}), HTTPStatus.NOT_FOUND)

    except SignatureExpired:
        return make_response(jsonify({'message': {
            'token': 'Expired'
        }}), HTTPStatus.FORBIDDEN)
    except:
        return make_response(jsonify({'message': {
            'token': 'Invalid value'
        }}), HTTPStatus.BAD_REQUEST)
Beispiel #6
0
def send():
    pass_secret = current_app.config.get('PASS_SECRET_KEY')
    pass_token_age = current_app.config.get('PASS_TOKEN_AGE')
    test_mode = current_app.config.get('TESTING')

    email = request.json.get('email')
    user = User.get_by_email(email)

    if user:
        singer = TimestampSigner(pass_secret)
        token_bytes = singer.sign(user.email)
        token = token_bytes.decode('utf-8')

        # Send token only for testing purposes
        if test_mode == True:
            return make_response(
                jsonify({
                    'message': 'Email has been sent',
                    'token': token
                }), HTTPStatus.ACCEPTED)

        # TODO: add sending email
        current_app.logger.info(
            'Reset password link: /password/reset?token=%s', token)

        return make_response(jsonify({'message': 'Email has been sent'}),
                             HTTPStatus.ACCEPTED)

    return make_response(jsonify({'message': {
        'email': 'Not found'
    }}), HTTPStatus.NOT_FOUND)
Beispiel #7
0
    def __init__(self):
        self.host = "127.0.0.1"
        self.port = 5000
        self.debug = False
        self.storage = None
        self.storage_settings = {}
        self.session = None
        self.session_settings = {}

        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = os.urandom(24)
        self.app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 31536000
        self.app.wsgi_app = ReverseProxied(self.app.wsgi_app)

        py_v = sys.version_info
        py_v = "%s.%s.%s" % (py_v[0], py_v[1], py_v[2])
        self.app.config.versions = {
            'python': py_v,
            'leselys': leselys.__version__,
            'flask': flask.__version__,
            'werkzeug': werkzeug.__version__,
            'celery': celery.__version__,
            'requests': requests.__version__
        }

        self.signer = TimestampSigner(self.app.config['SECRET_KEY'])
        self.cache = SimpleCache()
def test_two_factor_confirmed(app, client, auth, test_user,
                              get_two_factor_code):
    """Test that confirming two factor enables it."""
    uid, username, password = test_user
    # Log in first
    response, csrf_cookie = auth.login(username, password)
    with client:
        client.get("/")
        db_user = User.query.filter(User.id == uid).first()
        assert db_user.two_factor_auth is None
        response = client.post("/user/enable_two_factor",
                               headers={"X-CSRF-Token": csrf_cookie})
        assert 200 == response.status_code  # Should get an error

        json = response.get_json()
        secret = (TimestampSigner(app.config["SECRET_KEY"]).unsign(
            json["secret"], max_age=86400).decode())
        json["two_factor_code"] = get_two_factor_code(secret)
        response = client.post("/user/confirm_two_factor",
                               headers={"X-CSRF-Token": csrf_cookie},
                               json=json)
        assert response.status_code == 200
        assert response.json == {"two_factor_enabled": True}
        assert (User.query.filter(User.id == uid).first().two_factor_auth.
                decrypted_secret_key == secret)
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
def create_app(config_var=os.getenv('DEPLOY_ENV', 'Development')):
    # init application
    app = Flask(__name__)
    app.config.from_object('pxa.config.%sConfig' % config_var)

    # configure logger
    configure_logger(app)

    # configure celery
    celery.config_from_object(app.config)

    # configure elasticsearch
    es.init_app(app)

    # init database
    db.init_app(app)
    _module_dir = os.path.dirname(os.path.abspath(__file__))
    migrate.init_app(app, db, directory=os.path.join(_module_dir, '..', 'migrations'))  # noqa

    app.signer = TimestampSigner(app.config['SIGNER_KEY'])

    # register Blueprints
    from pxa.views.common import bp_common
    app.register_blueprint(bp_common)
    from pxa.views.website import bp_website
    app.register_blueprint(bp_website)

    # install error handler for views
    error_codes = [400, 401, 403, 404, 405, 406, 408, 409, 410, 412, 415, 428,
                   429, 500, 501]

    install_error_handlers(error_codes, app)
    return app
Beispiel #11
0
 def confirm_validate_token(self, token, expiration=3600):
     serializer = utsr(self.security_key)
     timeStamp = TimestampSigner(self.security_key)
     username = serializer.loads(token, salt=self.salt)
     username = timeStamp.unsign(username, max_age=expiration)
     print(username)
     return username
Beispiel #12
0
def parse_auth():
    """Parse the authentication token attached to the request.

    This function tries to retrieve the authentication token attached to the
    request by. It first looks for `X-Auth-Token` in the request headers. If
    no such header could be found, it checks for `Auth-Token` in the request
    cookies.

    The function returns the owner UID associated with the token attached to
    the request, or raises an exception if none of these locations contains a
    valid one.

    :raises ~trexmo.core.exc.InvalidTokenError:
        if the given token is missing or invalid.
    :raises ~trexmo.core.exc.ExpiredTokenError:
        if the given token expired.
    """
    auth_token = request.headers.get('X-Auth-Token', request.cookies.get('Auth-Token'))

    if auth_token is None:
        raise InvalidTokenError()

    signer = TimestampSigner(current_app.secret_key)

    try:
        auth = signer.unsign(auth_token, max_age=current_app.config['AUTH_TOKEN_DURATION'])
    except BadSignature:
        raise InvalidTokenError()
    except SignatureExpired:
        raise ExpiredTokenError()

    return auth.decode()
Beispiel #13
0
def verify_timed_token(token):
    s = TimestampSigner(SECRET_KEY)
    try:
        data = s.loads(token)
    except (SignatureExpired, BadSignature):
        return None
    return data
Beispiel #14
0
def create_app(loop):
    """Starts the aiohttp process to serve the REST API"""
    setproctitle('socialite-api')

    logger.debug("boot")

    # init app
    app = web.Application()  # pylint: disable=invalid-name
    app.on_startup.append(init_pg)
    app.middlewares.append(middleware_check_auth)
    app['settings'] = settings
    app['hasher'] = PasswordHasher()
    app['signer'] = TimestampSigner(settings.SECRET)

    # routes
    app.router.add_route('GET', '/api/status', status)
    app.router.add_route('POST', '/api/check_auth', check_auth)
    # routes for account
    app.router.add_route('POST', '/api/account/new', account_new)
    app.router.add_route('POST', '/api/account/login', account_login)
    # routes for wiki
    app.router.add_route('GET', '/api/wiki/{title}/latest', wiki_latest)
    app.router.add_route('POST', '/api/wiki/{title}/edit', wiki_edit)

    return app
Beispiel #15
0
 def setUp(self):
     src.main.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
     src.main.app.config['TESTING'] = True
     self.signer = TimestampSigner(secret)
     self.app = src.main.app.test_client()
     with src.main.app.app_context():
         src.main.init_app()
Beispiel #16
0
def email_check():
    """
    校验邮箱有效性
    http://localhost:5000/email/[email protected]
    """
    sign = request.args.get('sign', '')
    from itsdangerous import TimestampSigner, SignatureExpired, BadTimeSignature
    from app_frontend import app
    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 app_frontend.api.user_auth import update_user_auth_rows
        result = update_user_auth_rows({'verified': 1}, **{
            'type_auth': TYPE_AUTH_EMAIL,
            'auth_key': email
        })
        if result == 1:
            flash(u'%s, 邮箱成功激活' % email, 'success')
            return redirect(url_for('auth.index'))
        else:
            flash(u'%s, 邮箱激活失败' % email, 'warning')
    except SignatureExpired as e:
        # 处理签名超时
        flash(e.message, 'warning')
    except BadTimeSignature as e:
        # 处理签名错误
        flash(e.message, 'warning')
    return redirect(url_for('reg.index'))
Beispiel #17
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.index'))
Beispiel #18
0
def Register(request):
    restdata = {'data': '', 'regerror': ''}
    registerobj = forms.Register()  #实例化forms
    restdata['data'] = registerobj  #将对象传到模板中

    if request.method == 'POST':
        form = forms.Register(request.POST)
        if form.is_valid():
            username = request.POST['username']
            email = request.POST['email']
            password1 = request.POST['password1']
            password2 = request.POST['password2']
            if not Suser.objects.all().filter(email=email):  #先判断是否存在该用户
                if form.pwd_validate(password1, password2):  #判断密码是否一致
                    user = Suser.objects.create_user(email, username,
                                                     password1)
                    user.save()
                    #生成验证连接并发送邮件
                    s = TimestampSigner(django_settings.SECRET_KEY)
                    registerstring = s.sign(email)
                    sendmail.delay(dict(to=email,
                                        string=registerstring))  #发送邮件
                    return HttpResponseRedirect('/web/login/')
                else:
                    error = u'密码输入不一致!!'
                    restdata['regerror'] = error
            else:
                error = u'用户已存在,请重新输入!!!!!'
                restdata['regerror'] = error
        else:
            restdata['data'] = form
    return render(request, 'webapp/register.html', restdata)
Beispiel #19
0
async def read_item(request: Request, id: str):
    # TODO: check that the file  exist, if yes ..
    s = TimestampSigner('secret-key')
    try:
        filename = s.unsign(id, max_age=50).decode()
        return templates.TemplateResponse("download.html", {
            "request": request,
            "id": filename
        })
    except SignatureExpired:
        try:
            # check if is a file
            # Path(os.environ['DOWNLOAD_DIR'], str(id.rsplit('.', 2)[0])
            os.remove(
                Path(os.environ['DOWNLOAD_DIR'], str(id.rsplit('.', 2)[0])))
        except OSError:
            pass
        return templates.TemplateResponse("expired.html", {
            "request": request,
            "id": id
        })
    except BadSignature:
        return templates.TemplateResponse("error.html", {
            "request": request,
            "id": id
        })
Beispiel #20
0
def verifyCdata(cdata, secretkey, mxtime):
    s = TimestampSigner(secretkey)
    try:
        string = s.unsign(cdata, max_age=mxtime)
        return string
    except:
        return False
Beispiel #21
0
 def generate_session_token(self):
     timer = TimestampSigner(app.config["SECRET_KEY"])
     token = Serializer(app.config["SECRET_KEY"])
     return timer.sign(
         token.dumps({
             'userId': int(self.id)
         }).decode('utf-8')).decode('utf-8')
Beispiel #22
0
    async def token_find(self, token: str) -> int:
        """Return a user ID from a token.

        Parses the token to get the user ID and then unsigns it
        using the user's hashed password as a secret key
        """
        userid_encoded = token.split('.')[0]

        try:
            userid = int(base64.urlsafe_b64decode(userid_encoded))
        except (binascii.Error, ValueError):
            return None

        raw_user = self.get_raw_user(userid)
        if raw_user is None:
            return

        s = TimestampSigner(raw_user['password']['hash'])

        try:
            s.unsign(token)
        except itsdangerous.BadSignature:
            return

        return userid
Beispiel #23
0
def itsDecode(data: str,
              time: int = 15,
              url_safe_key: str = DEFAULT_SAFE_KEY,
              time_safe_key: str = DEFAULT_SAFE_KEY) -> (bool, str):
    '''
    @description: its解密
    @param {data} data 加密数据 
    @param {int}  time 过期时间
    @param {str}  url_safe_key URL加密密钥
    @param {str}  time_safe_key Time加密密钥
    @return: True/False, Data
    '''
    result = None
    time = int(time)
    try:
        tSafe = TimestampSigner(time_safe_key)
        tUnsign = tSafe.unsign(data, time)
    except:
        return False, "授权过期"
    try:
        uSafe = URLSafeSerializer(url_safe_key)
        result = uSafe.loads(url_safe_key)
        return True, result
    except:
        return False, "解析失败"
Beispiel #24
0
def channelstream_request(secret,
                          endpoint,
                          payload,
                          throw_exceptions=False,
                          servers=None):
    responses = []
    if not servers:
        servers = []

    signer = TimestampSigner(secret)
    sig_for_server = signer.sign(endpoint)
    for secret, server in [(s["secret"], s["server"]) for s in servers]:
        response = {}
        secret_headers = {
            "x-channelstream-secret": sig_for_server,
            "x-channelstream-endpoint": endpoint,
            "Content-Type": "application/json",
        }
        url = "%s%s" % (server, endpoint)
        try:
            response = requests.post(
                url,
                data=json.dumps(payload, cls=DateTimeEncoder),
                headers=secret_headers,
                verify=False,
                timeout=2,
            ).json()
        except requests.exceptions.RequestException as e:
            if throw_exceptions:
                raise
        responses.append(response)
    return responses
    def sign(self, unsigned_value, salt):
        """ Signs a value with a salt using itsdangerous.TimestampSigner and
        returns the resulting signed value.

        The salt might not be what you think it is:
        http://pythonhosted.org/itsdangerous/#the-salt
        """
        return TimestampSigner(self.secret, salt=salt).sign(unsigned_value)
Beispiel #26
0
 def sign(self, session_id):
     """
     签名 session_id
     :param session_id:
     :return:
     """
     s = TimestampSigner(self._sign_key)
     return s.sign(session_id)
Beispiel #27
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()))
    def test_verify_nonexistent_keyid(self):
        cookie_value = json.dumps({"A": "B", "key_id": "C"})

        signed_cookie = (TimestampSigner(
            secret_key="A").sign(cookie_value).decode("utf8"))

        with pytest.raises(exceptions.ServiceUnavailable):
            self.cookie_manager.verify(signed_cookie=signed_cookie)
Beispiel #29
0
async def send_path(loop):
    signer = TimestampSigner(args.key)
    message = signer.sign(args.path.encode('utf-8'))
    logger.debug('message: %s', message)

    _, writer = await asyncio.open_connection(args.host, args.port, loop=loop)
    writer.write(message)
    writer.close()
Beispiel #30
0
def generate_reset_token():
    s = TimestampSigner(
        "Secret")  # Creating a timestamp signer with an associated secret key
    string = s.sign("foo")  # Attaches time information of the signing
    print(s.unsign(
        string,
        max_age=20))  # Decrypts the received string with the timestamp signer
    return string