Added seed code for access-management.
[ta/access-management.git] / src / access_management / backend / authserver.py
1 # Copyright 2019 Nokia
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import json
16 import sys
17
18 from flask import Flask, request
19 from flask_restful import Resource, Api
20 from access_management.backend.ambackend import AMBackend
21 from access_management.config.amconfigparser import AMConfigParser
22 import access_management.backend.restlogger as restlog
23 from werkzeug.exceptions import InternalServerError
24
25 app = Flask(__name__)
26 api = Api(app)
27
28
29 class AuthorizeEndpoint(Resource):
30     def post(self):
31         backend = AMBackend(config)
32         params = json.loads(request.json['params'])
33         authorized, username = backend.is_authorized(token=params['token'], domain=params['domain'],
34                                                      domain_object=params['domain_object'], method=params['method'])
35         return {'authorized': authorized, 'username': username}
36
37
38 class AuthorizeRole(Resource):
39     def post(self):
40         backend = AMBackend(config)
41         authorized, username = backend.is_authorized(token=request.json['token'], role_name=request.json['role'])
42         return {'authorized': authorized, 'username': username}
43
44
45 # class DumpTables(Resource):
46 #     def get(self):
47 #         backend = AMBackend(config)
48 #         results = backend.dump_tables()
49 #         return results
50
51
52 api.add_resource(AuthorizeEndpoint, '/authorize/endpoint')
53 api.add_resource(AuthorizeRole, '/authorize/role')
54 # api.add_resource(DumpTables, '/dumptables')
55
56
57 def main():
58     global config
59     configparser = AMConfigParser("/etc/access_management/am_backend_config.ini")
60     config = configparser.parse()
61     logger = restlog.get_logger(config)
62     initialize(config,logger)
63     app.run(host=config["Api"]["host"], port=int(config["Api"]["port"]), debug=True)
64
65
66 def initialize(config, logger):
67     logger.info("Initializing...")
68     app.register_error_handler(Exception, handle_exp)
69     app.before_request(request_logger)
70     app.after_request(response_logger)
71     app.logger.addHandler(restlog.get_log_handler(config))
72     logger.info("Starting up...")
73
74
75 def request_logger():
76     app.logger.info('Request: remote_addr: %s method: %s endpoint: %s', request.remote_addr, request.method,
77                     request.full_path)
78
79
80 def response_logger(response):
81     app.logger.info('Response: status: %s (Associated Request: remote_addr: %s, method: %s, endpoint: %s)',
82                     response.status, request.remote_addr, request.method, request.full_path)
83
84     app.logger.debug('Response\'s data: %s', response.data)
85
86     return response
87
88
89 def handle_exp(failure):
90     app.logger.error("Internal error: %s ", failure)
91     raise InternalServerError()
92
93
94 if __name__ == '__main__':
95     try:
96         sys.exit(main())
97     except Exception as error:# pylint: disable=broad-except
98         print "Failure: %s" % error
99         sys.exit(255)