Esempio n. 1
0
 def anxiety_from_date(self):
     if cherrypy.request.method == 'OPTIONS':
         # This is a request that browser sends in CORS prior to
         # sending a real request.
         # Set up extra headers for a pre-flight OPTIONS request.
         cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
     if cherrypy.request.method == 'POST':
         data = cherrypy.request.json
         fileToOpen = "./data/" + data["date"][:10]
         # add multiple users stuff later
         ret = json.dumps("")
         try:
             f = open(fileToOpen + ".json", "r")
             jsonData = json.load(f)
             f.close()
             if jsonData["heartRateValues"]:
                 dataFrame = pd.DataFrame(jsonData["heartRateValues"])
                 dataFrame["datetime"] = pd.to_datetime(jsonData["date"] +
                                                        " " +
                                                        dataFrame["time"])
                 ret = p.find_anxious_times(dataFrame)
                 self.write_file_anxiety_values(data["date"], ret)
         except Exception as e:
             traceback.print_exc()
         return ret
     return "Non-POST"
Esempio n. 2
0
    def index(self, op, **kwargs):
        if cherrypy.request.method == "OPTIONS":
            cherrypy_cors.preflight(
                allowed_methods=["POST", "GET"], origins='*',
                allowed_headers=['Authorization', 'content-type'])
        else:
            store_request(op, 'Logout')
            logger.debug('LogoutRequest: {}'.format(kwargs))
            op.events.store(EV_REQUEST, kwargs)

            # Normally the user would here be confronted with a logout
            # verification page. We skip that and assumes she said yes.

            _info = op.unpack_signed_jwt(kwargs['sjwt'])
            logger.debug("SJWT unpacked: {}".format(_info))
            # Before continuing make sure only the channel under test is used
            # for cid, _c_info in op.cdb.items():

            try:
                res = op.do_verified_logout(alla=True, **_info)
            except ConnectionRefusedError as err:
                logger.error(err)
                raise cherrypy.HTTPError(message="Connection Refused: {}".format(err))
            except Exception as err:
                logger.exception(err)
                raise cherrypy.HTTPError(message="{}".format(err))

            if res == {}:  # Failed
                raise cherrypy.HTTPError(
                    message="Backchannel logout failed. No Frontchannel logout defined")

            _iframes = []
            if res:
                try:
                    _iframes = res['iframe']
                except (KeyError, TypeError):
                    pass

            _state = _info.get("state")
            if _state:
                _redirect_uri = "{}?{}".format(_info['redirect_uri'],
                                               urlencode({"state":_info["state"]}))
            else:
                _redirect_uri = _info['redirect_uri']

            _body = LOGOUT_HTML_BODY.replace('{size}', str(len(_iframes)))
            _body = _body.replace('{frames}', ''.join(_iframes))
            _body = _body.replace('{timeout}', '30')
            _body = _body.replace('{postLogoutRedirectUri}', _redirect_uri)

            try:
                cookies = res['cookie']
            except (KeyError, TypeError):
                pass
            else:
                for tag, val in cookies:
                    logger.debug("Response cookie: %s", val)
                    cherrypy.response.cookie.load(val)

            return as_bytes("\n".join([LOGOUT_HTML_HEAD, _body]))
Esempio n. 3
0
    def index(self, op, **kwargs):
        if cherrypy.request.method == "OPTIONS":
            cherrypy_cors.preflight(
                allowed_methods=["GET"],
                origins='*',
                allowed_headers=['Authorization', 'content-type'])
        else:
            store_request(op, 'EndSessionRequest')
            logger.debug('EndSessionRequest: {}'.format(kwargs))
            # op.events.store(EV_REQUEST, kwargs)
            cookie = cherrypy.request.cookie
            if cookie:
                logger.debug("Request cookie at end_session_endpoint: %s",
                             cookie)
            _info = Message(**kwargs)
            if "post_logout_redirect_uri" in _info:
                if not 'id_token_hint' in _info:
                    raise cherrypy.HTTPError(
                        400,
                        message=
                        "If 'post_logout_redirect_uri' then 'id_token_hint' is a MUST"
                    )

            resp = op.end_session_endpoint(_info.to_urlencoded(),
                                           cookie=cookie)
            # Normally the user would here be confronted with a logout
            # verification page. We skip that and just assumes she said yes.

            return conv_response(op, resp)
Esempio n. 4
0
File: cpop.py Progetto: rohe/fedoidc
    def registration(self, **kwargs):
        logger.debug('Request headers: {}'.format(cherrypy.request.headers))
        if cherrypy.request.method == "OPTIONS":
            cherrypy_cors.preflight(
                allowed_methods=["POST", "GET"],
                origins='*',
                allowed_headers=['Authorization', 'content-type'])
        elif cherrypy.request.method == "GET":
            _cinfo = self.op.cdb[kwargs['client_id']]
            for attr in ['redirect_uris', 'post_logout_redirect_uris']:
                try:
                    _cinfo[attr] = unpack_redirect_uri(_cinfo[attr])
                except KeyError:
                    pass
            rr = RegistrationResponse(**_cinfo)
            cherrypy.response.headers['Content-Type'] = 'application/json'
            return as_bytes(json.dumps(rr.to_dict()))
        else:
            logger.debug('ClientRegistration kwargs: {}'.format(kwargs))
            _request = None

            if cherrypy.request.process_request_body is True:
                _request = as_unicode(cherrypy.request.body.read())
                logger.debug('request_body: {}'.format(_request))

            try:
                if _request:
                    resp = self.op.registration_endpoint(_request)
                else:
                    resp = self.op.registration_endpoint(kwargs)
            except Exception as err:
                logger.error(err)
                raise cherrypy.HTTPError(message=str(err))

            return conv_response(resp)
Esempio n. 5
0
File: op.py Progetto: rohe/oidctest
    def index(self, op, **kwargs):
        if cherrypy.request.method == "OPTIONS":
            cherrypy_cors.preflight(
                allowed_methods=["GET"], origins='*',
                allowed_headers='Authorization')
        else:
            try:
                authz = cherrypy.request.headers['Authorization']
            except KeyError:
                authz = None
            try:
                assert authz.startswith("Bearer")
            except AssertionError:
                op.events.store(EV_FAULT, "Bad authorization token")
                cherrypy.HTTPError(400, "Bad authorization token")

            tok = authz[7:]
            try:
                _claims = op.claim_access_token[tok]
            except KeyError:
                op.events.store(EV_FAULT, "Bad authorization token")
                cherrypy.HTTPError(400, "Bad authorization token")
            else:
                # one time token
                del op.claim_access_token[tok]
                _info = Message(**_claims)
                jwt_key = op.keyjar.get_signing_key()
                op.events.store(EV_RESPONSE, _info.to_dict())
                cherrypy.response.headers["content-type"] = 'application/jwt'
                return as_bytes(_info.to_jwt(key=jwt_key, algorithm="RS256"))
Esempio n. 6
0
    def index(self, op, **kwargs):
        if cherrypy.request.method == "OPTIONS":
            cherrypy_cors.preflight(allowed_methods=["GET"],
                                    origins='*',
                                    allowed_headers='Authorization')
        else:
            try:
                authz = cherrypy.request.headers['Authorization']
            except KeyError:
                authz = None
            try:
                assert authz.startswith("Bearer")
            except AssertionError:
                op.events.store(EV_FAULT, "Bad authorization token")
                cherrypy.HTTPError(400, "Bad authorization token")

            tok = authz[7:]
            try:
                _claims = op.claim_access_token[tok]
            except KeyError:
                op.events.store(EV_FAULT, "Bad authorization token")
                cherrypy.HTTPError(400, "Bad authorization token")
            else:
                # one time token
                del op.claim_access_token[tok]
                _info = Message(**_claims)
                jwt_key = op.keyjar.get_signing_key()
                op.events.store(EV_RESPONSE, _info.to_dict())
                cherrypy.response.headers["content-type"] = 'application/jwt'
                return as_bytes(_info.to_jwt(key=jwt_key, algorithm="RS256"))
Esempio n. 7
0
    def index(self):
        rslt = ""
        try:
            if cherrypy.request.method == 'OPTIONS':
                # This is a request that browser sends in CORS prior to
                # sending a real request.

                # Set up extra headers for a pre-flight OPTIONS request.
                cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])

            if cherrypy.request.method == 'POST':
                print("reach server")
                header = cherrypy.request.headers
                rawData = cherrypy.request.body.read(
                    int(cherrypy.request.headers['Content-Length'])).decode(
                        'utf-8')
                body = json.loads(rawData)
                #function call to route the header
                userid = body["datahdr"]["userid"]
                logging.config.fileConfig("loggers.conf",
                                          defaults={'logfilename': userid},
                                          disable_existing_loggers=False)

                rslt = json.dumps(routeRequest(body, header))
                #rslt = json.dumps({"name":"vignesh"})
                logging.debug(rslt)
                #rslt="take it"
            else:
                rslt = "Method not allowed"
        except:
            rslt = "Excetion occurs"
            print("Exception occurs")
            traceback.print_exc()
        return rslt
Esempio n. 8
0
    def is_user_anxious(self):
        if cherrypy.request.method == 'OPTIONS':
            # This is a request that browser sends in CORS prior to
            # sending a real request.
            # Set up extra headers for a pre-flight OPTIONS request.
            cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])

        if cherrypy.request.method == 'POST':
            data = cherrypy.request.json
            fileToOpen = "./data/" + data["date"][:10]
            # add multiple users stuff later
            ret = ""
            try:
                f = open(fileToOpen + ".json", "r")
                jsonData = json.load(f)
                f.close()
                dataFrame = pd.DataFrame(jsonData["heartRateValues"])
                dataFrame["datetime"] = pd.to_datetime(jsonData["date"] + " " +
                                                       dataFrame["time"])
                date = pd.to_datetime(data["date"])
                ret = p.is_user_anxious(dataFrame, date, data["time"])
            except Exception as e:
                traceback.print_exc()
                ret = traceback._cause_message
            return ret.__str__()
        return "Non-POST"
Esempio n. 9
0
 def index(self):
     if cherrypy.request.method == 'OPTIONS':
         cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
     elif cherrypy.request.method == 'GET':
         return "Hello in subtitle API!"
     else:
         raise cherrypy.HTTPError(400)
Esempio n. 10
0
 def index(self, item='', **kwargs):
     if cherrypy.request.method == "OPTIONS":
         cherrypy_cors.preflight(
             allowed_methods=["GET"],
             origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         return as_bytes(self.smsfs[item])
Esempio n. 11
0
 def index(self, op, **kwargs):
     if cherrypy.request.method == "OPTIONS":
         cherrypy_cors.preflight(
             allowed_methods=["GET"], origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         logger.debug('AuthorizationRequest')
         resp = op.authorization_endpoint(kwargs)
         return conv_response(resp)
Esempio n. 12
0
 def verify(self, **kwargs):
     if cherrypy.request.method == "OPTIONS":
         cherrypy_cors.preflight(
             allowed_methods=["POST", "GET"], origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         logger.debug('AuthorizationRequest')
         resp, state = self.op.verify_endpoint(kwargs)
         return conv_response(resp)
Esempio n. 13
0
    def get_model_results(self):

        if cherrypy.request.method == 'OPTIONS':
            cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
            return ''

        full_file_name = os.path.join(absDir, 'model.txt')
        file_content = open(full_file_name).read()

        cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
        return file_content
Esempio n. 14
0
 def index(self, op, **kwargs):
     if cherrypy.request.method == "OPTIONS":
         cherrypy_cors.preflight(
             allowed_methods=["GET"], origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         store_request(op, 'AuthorizationRequest')
         logger.debug('AuthorizationRequest: {}'.format(kwargs))
         op.events.store(EV_REQUEST, kwargs)
         resp = op.authorization_endpoint(kwargs)
         return conv_response(op, resp)
Esempio n. 15
0
 def check(self):
     """ Checks the user's token and returns its password + extra data. """
     if cherrypy.request.method == 'OPTIONS':
         cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
         return
     if cherrypy.request.method != "POST":
         raise cherrypy.HTTPError(
             400, "Invalid request (%s)" % cherrypy.request.method)
     args = cherrypy.request.json
     user_obj = self._check_user(args)
     return self._get_extra_creds(user_obj)
Esempio n. 16
0
File: op.py Progetto: rohe/oidctest
 def index(self, op, **kwargs):
     if cherrypy.request.method == "OPTIONS":
         cherrypy_cors.preflight(
             allowed_methods=["GET"], origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         store_request(op, 'AuthorizationRequest')
         logger.debug('AuthorizationRequest: {}'.format(kwargs))
         op.events.store(EV_REQUEST, kwargs)
         resp = op.authorization_endpoint(kwargs)
         return conv_response(op, resp)
Esempio n. 17
0
File: op.py Progetto: rohe/oidctest
 def index(self, op, test_id, client_id):
     if cherrypy.request.method == "OPTIONS":
         logger.debug('Request headers: {}'.format(cherrypy.request.headers))
         cherrypy_cors.preflight(
             allowed_methods=["GET"],
             allowed_headers=['Authorization', 'content-type'],
             allow_credentials=True, origins='*'
         )
     else:
         if test_id == "rp-3rd_party-init-login":
             return self.rp_3rd_party_init_login(op, client_id)
         raise cherrypy.HTTPError(404, "no test handler found for test id: " + test_id)
Esempio n. 18
0
 def index(self, op, test_id, client_id):
     if cherrypy.request.method == "OPTIONS":
         logger.debug('Request headers: {}'.format(cherrypy.request.headers))
         cherrypy_cors.preflight(
             allowed_methods=["GET"],
             allowed_headers=['Authorization', 'content-type'],
             allow_credentials=True, origins='*'
         )
     else:
         if test_id == "rp-3rd_party-init-login":
             return self.rp_3rd_party_init_login(op, client_id)
         raise cherrypy.HTTPError(404, "no test handler found for test id: " + test_id)
Esempio n. 19
0
 def index(self, op):
     if cherrypy.request.method == "OPTIONS":
         logger.debug('Request headers: {}'.format(cherrypy.request.headers))
         cherrypy_cors.preflight(
             allowed_methods=["GET"],
             allowed_headers=['Authorization', 'content-type'],
             allow_credentials=True, origins='*'
         )
     else:
         logger.debug('ProviderInfo request')
         resp = op.providerinfo_endpoint()
         # cherrypy.response.headers['Content-Type'] = 'application/json'
         # return as_bytes(resp.message)
         return conv_response(resp)
Esempio n. 20
0
File: op.py Progetto: rohe/oidctest
 def index(self, op):
     if cherrypy.request.method == "OPTIONS":
         logger.debug('Request headers: {}'.format(cherrypy.request.headers))
         cherrypy_cors.preflight(
             allowed_methods=["GET"],
             allowed_headers=['Authorization', 'content-type'],
             allow_credentials=True, origins='*'
         )
     else:
         store_request(op, 'ProviderInfo')
         resp = op.providerinfo_endpoint()
         if resp.status_code < 300:
             set_content_type(resp, 'application/json')
         return conv_response(op, resp)
Esempio n. 21
0
 def index(self, op, **kwargs):
     if cherrypy.request.method == "OPTIONS":
         cherrypy_cors.preflight(
             allowed_methods=["POST"], origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         logger.debug('AccessTokenRequest')
         try:
             authn = cherrypy.request.headers['Authorization']
         except KeyError:
             authn = None
         logger.debug('Authorization: {}'.format(authn))
         resp = op.token_endpoint(as_unicode(kwargs), authn, 'dict')
         return conv_response(resp)
Esempio n. 22
0
 def index(self, op):
     if cherrypy.request.method == "OPTIONS":
         logger.debug('Request headers: {}'.format(cherrypy.request.headers))
         cherrypy_cors.preflight(
             allowed_methods=["GET"],
             allowed_headers=['Authorization', 'content-type'],
             allow_credentials=True, origins='*'
         )
     else:
         store_request(op, 'ProviderInfo')
         resp = op.providerinfo_endpoint()
         if resp.status_code < 300:
             set_content_type(resp, 'application/json')
         return conv_response(op, resp)
Esempio n. 23
0
File: op.py Progetto: rohe/oidctest
 def index(self, op, **kwargs):
     if cherrypy.request.method == "OPTIONS":
         cherrypy_cors.preflight(
             allowed_methods=["POST"], origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         store_request(op, 'AccessTokenRequest')
         try:
             authn = cherrypy.request.headers['Authorization']
         except KeyError:
             authn = None
         logger.debug('Authorization: {}'.format(authn))
         resp = op.token_endpoint(as_unicode(kwargs), authn, 'dict')
         if resp.status_code < 300:
             set_content_type(resp, 'application/json')
         return conv_response(op, resp)
Esempio n. 24
0
 def index(self, op):
     if cherrypy.request.method == "OPTIONS":
         logger.debug('Request headers: {}'.format(cherrypy.request.headers))
         cherrypy_cors.preflight(
             allowed_methods=["POST"], origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         logger.debug('ClientRegistration request')
         if cherrypy.request.process_request_body is True:
             _request = cherrypy.request.body.read()
         else:
             raise cherrypy.HTTPError(400,
                                      'Missing Client registration body')
         logger.debug('request_body: {}'.format(_request))
         resp = op.registration_endpoint(as_unicode(_request))
         return conv_response(resp)
Esempio n. 25
0
File: op.py Progetto: rohe/oidctest
 def index(self, op):
     if cherrypy.request.method == "OPTIONS":
         logger.debug('Request headers: {}'.format(cherrypy.request.headers))
         cherrypy_cors.preflight(
             allowed_methods=["POST"], origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         store_request(op, 'ClientRegistration')
         if cherrypy.request.process_request_body is True:
             _request = cherrypy.request.body.read()
         else:
             raise cherrypy.HTTPError(400,
                                      'Missing Client registration body')
         logger.debug('request_body: {}'.format(_request))
         resp = op.registration_endpoint(as_unicode(_request))
         if resp.status_code < 300:
             set_content_type(resp, 'application/json')
         return conv_response(op, resp)
Esempio n. 26
0
 def index(self, op, **kwargs):
     if cherrypy.request.method == "OPTIONS":
         cherrypy_cors.preflight(
             allowed_methods=["GET", "POST"], origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         store_request(op, 'CheckSessionIframe')
         logger.debug('CheckSessionIframe: {}'.format(kwargs))
         if cherrypy.request.method == "POST":
             _req = cherrypy.request.body.read()
             kwargs = json.loads(as_unicode(_req))
             # will contain client_id and origin
             if kwargs['client_id'] not in op.cdb:
                 return b'error'
             # Should have some intelligent check for origin
             return b'ok'
         else:
             doc = open('templates/check_session_iframe.html').read()
             return as_bytes(doc)
Esempio n. 27
0
 def token(self, **kwargs):
     if cherrypy.request.method == "OPTIONS":
         cherrypy_cors.preflight(
             allowed_methods=["POST"],
             origins='*',
             allowed_headers=['Authorization', 'content-type'])
     else:
         logger.debug('AccessTokenRequest')
         try:
             authn = cherrypy.request.headers['Authorization']
         except KeyError:
             authn = None
         logger.debug('Authorization: {}'.format(authn))
         try:
             resp = self.op.token_endpoint(kwargs, authn, 'dict')
         except Exception as err:
             raise cherrypy.HTTPError(message=str(err))
         else:
             return conv_response(resp)
Esempio n. 28
0
    def index(self, op, **kwargs):
        if cherrypy.request.method == "OPTIONS":
            cherrypy_cors.preflight(
                allowed_methods=["GET", "POST"], origins='*',
                allowed_headers=['Authorization', 'content-type'])
        else:
            logger.debug('UserinfoRequest')
            if cherrypy.request.process_request_body is True:
                args = {'request': cherrypy.request.body.read()}
            else:
                args = {}
            try:
                args['authn'] = cherrypy.request.headers['Authorization']
            except KeyError:
                pass

            kwargs.update(args)
            resp = op.userinfo_endpoint(**kwargs)
            return conv_response(resp)
Esempio n. 29
0
    def index(self, op):
        if cherrypy.request.method == "OPTIONS":
            logger.debug('Request headers: {}'.format(
                cherrypy.request.headers))
            cherrypy_cors.preflight(
                allowed_methods=["GET"],
                allowed_headers=['Authorization', 'content-type'],
                allow_credentials=True,
                origins='*')
        else:
            store_request(op, 'ProviderInfo')
            try:
                resp = op.create_fed_providerinfo()
            except Exception as err:
                raise cherrypy.HTTPError(message=as_bytes(err))

            cherrypy.response.headers['Content-Type'] = 'application/json'
            # return as_bytes(resp.message)
            return as_bytes(json.dumps(resp.to_dict()))
Esempio n. 30
0
    def write_file(self):
        if cherrypy.request.method == 'OPTIONS':
            # This is a request that browser sends in CORS prior to
            # sending a real request.
            # Set up extra headers for a pre-flight OPTIONS request.
            cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])

        if cherrypy.request.method == 'POST':
            data = cherrypy.request.json
            ret = ""
            try:
                f = open("./data/" + data["date"][:10] + ".json", "w")
                json.dump(data, f)
                f.close()
                ret = "Sucessfully wrote to file"
            except Exception as e:
                print("Error", e.__str__())
                ret = json.dumps({'error': e.__str__()})
            return ret
        return "Non-POST"
Esempio n. 31
0
    def weekly_pattern(self):
        # startDate
        # endDate
        if cherrypy.request.method == 'OPTIONS':
            # This is a request that browser sends in CORS prior to
            # sending a real request.
            # Set up extra headers for a pre-flight OPTIONS request.
            cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
        if cherrypy.request.method == 'POST':
            data = cherrypy.request.json
            startDate = pd.to_datetime(data["startDate"])
            endDate = pd.to_datetime(data["endDate"])
            print("Looking for files from ", startDate.strftime("%Y-%m-%d"),
                  " to ", endDate.strftime("%Y-%m-%d"))
            dateRange = pd.date_range(start=startDate, end=endDate)
            dataFrame = pd.DataFrame()
            for date in dateRange:
                date = pd.to_datetime(date)
                tempDataFrame = pd.DataFrame()
                fileToOpen = "./data/" + date.strftime("%Y-%m-%d")
                try:
                    f = open(fileToOpen + "-anxiety.json", "r")
                    jsonData = json.load(f)
                    f.close()
                    tempDataFrame = pd.read_json(jsonData)
                    print("Found data for date ", date.strftime("%Y-%m-%d"))
                    if not (dataFrame.empty):
                        dataFrame = dataFrame.append(tempDataFrame,
                                                     ignore_index=True)
                    else:
                        dataFrame = tempDataFrame
                except FileNotFoundError:
                    print("No data exists for date ",
                          date.strftime("%Y-%m-%d"))
                except Exception:
                    traceback.print_exc()
            print("final data to analyze for weekly patterns", dataFrame)
            ret = p.weekly_pattern(dataFrame)
            return ret

        return "Non-POST"
Esempio n. 32
0
File: cpop.py Progetto: rohe/fedoidc
    def index(self, op):
        if cherrypy.request.method == "OPTIONS":
            logger.debug('Request headers: {}'.format(
                cherrypy.request.headers))
            cherrypy_cors.preflight(
                allowed_methods=["GET"],
                allowed_headers=['Authorization', 'content-type'],
                allow_credentials=True,
                origins='*')
        else:
            logger.debug('ProviderInfo request')

            try:
                _ = op.federation_entity  # Federation aware ?
            except AttributeError:
                resp = op.providerinfo_endpoint()
                return conv_response(resp)
            else:
                resp = op.create_fed_providerinfo()
                cherrypy.response.headers['Content-Type'] = 'application/json'
                return as_bytes(json.dumps(resp.to_dict()))
Esempio n. 33
0
    def new_credentials(self):
        if cherrypy.request.method == 'OPTIONS':
            cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
            return
        if cherrypy.request.method != "POST":
            raise cherrypy.HTTPError(
                400, "Invalid request (%s)" % cherrypy.request.method)
        args = cherrypy.request.json
        if not isinstance(args, Mapping) or "labPassword" not in args:
            raise cherrypy.HTTPError(400, "Invalid request data")
        if not self._store.lab.check_password(args["labPassword"]):
            raise cherrypy.HTTPError(400, "Wrong lab password")

        try:
            user_obj = self._store.users.allocate_user()
        except StudentAccountException as exc:
            self._log.warn("User allocation failed")
            raise cherrypy.HTTPError(500, str(exc))

        self._log.info("Allocated user: %s", user_obj.username)

        return self._get_extra_creds(user_obj)
Esempio n. 34
0
    def index(self, op, **kwargs):
        if cherrypy.request.method == "OPTIONS":
            cherrypy_cors.preflight(
                allowed_methods=["GET", "POST"],
                origins='*',
                allowed_headers=['Authorization', 'content-type'])
        else:
            store_request(op, 'UserinfoRequest')
            args = {'request': kwargs}
            if cherrypy.request.process_request_body is True:
                _req = cherrypy.request.body.read()
                if _req:  # The request is either in kwargs or in body
                    args['request'] = _req

            try:
                args['authn'] = cherrypy.request.headers['Authorization']
            except KeyError:
                pass

            #kwargs.update(args)
            resp = op.userinfo_endpoint(**args)
            return conv_response(op, resp)
Esempio n. 35
0
    def authorization(self, **kwargs):
        if cherrypy.request.method == "OPTIONS":
            cherrypy_cors.preflight(
                allowed_methods=["GET"], origins='*',
                allowed_headers=['Authorization', 'content-type'])
        else:
            logger.debug('AuthorizationRequest')
            try:
                args = {'cookie': cherrypy.request.headers['Cookie']}
            except KeyError:
                args = {}

            try:
                _claims = json.loads(kwargs['claims'])
            except json.JSONDecodeError:
                try:
                    _claims = json.loads(
                        kwargs['claims'].replace("\'", '"').replace('True',
                                                                    'true'))
                except json.JSONDecodeError:
                    _err = ErrorResponse(
                        error="invalid_request",
                        error_description="Invalid claims value"
                    )
                    raise cherrypy.HTTPError(400, as_bytes(_err.to_json()))
                else:
                    kwargs['claims'] = _claims
            except KeyError:
                pass
            else:
                kwargs['claims'] = _claims

            try:
                resp = self.op.authorization_endpoint(kwargs, **args)
            except Exception as err:
                raise cherrypy.HTTPError(message=err)
            else:
                return conv_response(resp)
Esempio n. 36
0
File: op.py Progetto: rohe/oidctest
    def index(self, op, **kwargs):
        if cherrypy.request.method == "OPTIONS":
            cherrypy_cors.preflight(
                allowed_methods=["GET", "POST"], origins='*',
                allowed_headers=['Authorization', 'content-type'])
        else:
            store_request(op, 'UserinfoRequest')
            args = {'request': kwargs}
            if cherrypy.request.process_request_body is True:
                _req = cherrypy.request.body.read()
                if _req:  # The request is either in kwargs or in body
                    args['request'] = _req

            try:
                args['authn'] = cherrypy.request.headers['Authorization']
            except KeyError:
                pass

            #kwargs.update(args)
            resp = op.userinfo_endpoint(**args)
            #if resp.status_code < 300:
            #    set_content_type(resp, 'application/json')
            return conv_response(op, resp)
Esempio n. 37
0
 def _check_preflight(self):
     """ Checks for CORS preflight and returns from the request. """
     if cherrypy.request.method == 'OPTIONS':
         cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
         return True
     return False