1#!/usr/bin/python
2from __future__ import (absolute_import, division, print_function)
3# Copyright 2019 Fortinet, Inc.
4#
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
18__metaclass__ = type
19
20ANSIBLE_METADATA = {'status': ['preview'],
21                    'supported_by': 'community',
22                    'metadata_version': '1.1'}
23
24DOCUMENTATION = '''
25---
26module: fortios_wireless_controller_hotspot20_anqp_network_auth_type
27short_description: Configure network authentication type in Fortinet's FortiOS and FortiGate.
28description:
29    - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
30      user to set and modify wireless_controller_hotspot20 feature and anqp_network_auth_type category.
31      Examples include all parameters and values need to be adjusted to datasources before usage.
32      Tested with FOS v6.0.5
33version_added: "2.9"
34author:
35    - Miguel Angel Munoz (@mamunozgonzalez)
36    - Nicolas Thomas (@thomnico)
37notes:
38    - Requires fortiosapi library developed by Fortinet
39    - Run as a local_action in your playbook
40requirements:
41    - fortiosapi>=0.9.8
42options:
43    host:
44        description:
45            - FortiOS or FortiGate IP address.
46        type: str
47        required: false
48    username:
49        description:
50            - FortiOS or FortiGate username.
51        type: str
52        required: false
53    password:
54        description:
55            - FortiOS or FortiGate password.
56        type: str
57        default: ""
58    vdom:
59        description:
60            - Virtual domain, among those defined previously. A vdom is a
61              virtual instance of the FortiGate that can be configured and
62              used as a different unit.
63        type: str
64        default: root
65    https:
66        description:
67            - Indicates if the requests towards FortiGate must use HTTPS protocol.
68        type: bool
69        default: true
70    ssl_verify:
71        description:
72            - Ensures FortiGate certificate must be verified by a proper CA.
73        type: bool
74        default: true
75    state:
76        description:
77            - Indicates whether to create or remove the object.
78        type: str
79        required: true
80        choices:
81            - present
82            - absent
83    wireless_controller_hotspot20_anqp_network_auth_type:
84        description:
85            - Configure network authentication type.
86        default: null
87        type: dict
88        suboptions:
89            auth_type:
90                description:
91                    - Network authentication type.
92                type: str
93                choices:
94                    - acceptance-of-terms
95                    - online-enrollment
96                    - http-redirection
97                    - dns-redirection
98            name:
99                description:
100                    - Authentication type name.
101                required: true
102                type: str
103            url:
104                description:
105                    - Redirect URL.
106                type: str
107'''
108
109EXAMPLES = '''
110- hosts: localhost
111  vars:
112   host: "192.168.122.40"
113   username: "admin"
114   password: ""
115   vdom: "root"
116   ssl_verify: "False"
117  tasks:
118  - name: Configure network authentication type.
119    fortios_wireless_controller_hotspot20_anqp_network_auth_type:
120      host:  "{{ host }}"
121      username: "{{ username }}"
122      password: "{{ password }}"
123      vdom:  "{{ vdom }}"
124      https: "False"
125      state: "present"
126      wireless_controller_hotspot20_anqp_network_auth_type:
127        auth_type: "acceptance-of-terms"
128        name: "default_name_4"
129        url: "myurl.com"
130'''
131
132RETURN = '''
133build:
134  description: Build number of the fortigate image
135  returned: always
136  type: str
137  sample: '1547'
138http_method:
139  description: Last method used to provision the content into FortiGate
140  returned: always
141  type: str
142  sample: 'PUT'
143http_status:
144  description: Last result given by FortiGate on last operation applied
145  returned: always
146  type: str
147  sample: "200"
148mkey:
149  description: Master key (id) used in the last call to FortiGate
150  returned: success
151  type: str
152  sample: "id"
153name:
154  description: Name of the table used to fulfill the request
155  returned: always
156  type: str
157  sample: "urlfilter"
158path:
159  description: Path of the table used to fulfill the request
160  returned: always
161  type: str
162  sample: "webfilter"
163revision:
164  description: Internal revision number
165  returned: always
166  type: str
167  sample: "17.0.2.10658"
168serial:
169  description: Serial number of the unit
170  returned: always
171  type: str
172  sample: "FGVMEVYYQT3AB5352"
173status:
174  description: Indication of the operation's result
175  returned: always
176  type: str
177  sample: "success"
178vdom:
179  description: Virtual domain used
180  returned: always
181  type: str
182  sample: "root"
183version:
184  description: Version of the FortiGate
185  returned: always
186  type: str
187  sample: "v5.6.3"
188
189'''
190
191from ansible.module_utils.basic import AnsibleModule
192from ansible.module_utils.connection import Connection
193from ansible.module_utils.network.fortios.fortios import FortiOSHandler
194from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
195
196
197def login(data, fos):
198    host = data['host']
199    username = data['username']
200    password = data['password']
201    ssl_verify = data['ssl_verify']
202
203    fos.debug('on')
204    if 'https' in data and not data['https']:
205        fos.https('off')
206    else:
207        fos.https('on')
208
209    fos.login(host, username, password, verify=ssl_verify)
210
211
212def filter_wireless_controller_hotspot20_anqp_network_auth_type_data(json):
213    option_list = ['auth_type', 'name', 'url']
214    dictionary = {}
215
216    for attribute in option_list:
217        if attribute in json and json[attribute] is not None:
218            dictionary[attribute] = json[attribute]
219
220    return dictionary
221
222
223def underscore_to_hyphen(data):
224    if isinstance(data, list):
225        for elem in data:
226            elem = underscore_to_hyphen(elem)
227    elif isinstance(data, dict):
228        new_data = {}
229        for k, v in data.items():
230            new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
231        data = new_data
232
233    return data
234
235
236def wireless_controller_hotspot20_anqp_network_auth_type(data, fos):
237    vdom = data['vdom']
238    state = data['state']
239    wireless_controller_hotspot20_anqp_network_auth_type_data = data['wireless_controller_hotspot20_anqp_network_auth_type']
240    filtered_data = \
241        underscore_to_hyphen(filter_wireless_controller_hotspot20_anqp_network_auth_type_data(wireless_controller_hotspot20_anqp_network_auth_type_data))
242
243    if state == "present":
244        return fos.set('wireless-controller.hotspot20',
245                       'anqp-network-auth-type',
246                       data=filtered_data,
247                       vdom=vdom)
248
249    elif state == "absent":
250        return fos.delete('wireless-controller.hotspot20',
251                          'anqp-network-auth-type',
252                          mkey=filtered_data['name'],
253                          vdom=vdom)
254
255
256def is_successful_status(status):
257    return status['status'] == "success" or \
258        status['http_method'] == "DELETE" and status['http_status'] == 404
259
260
261def fortios_wireless_controller_hotspot20(data, fos):
262
263    if data['wireless_controller_hotspot20_anqp_network_auth_type']:
264        resp = wireless_controller_hotspot20_anqp_network_auth_type(data, fos)
265
266    return not is_successful_status(resp), \
267        resp['status'] == "success", \
268        resp
269
270
271def main():
272    fields = {
273        "host": {"required": False, "type": "str"},
274        "username": {"required": False, "type": "str"},
275        "password": {"required": False, "type": "str", "default": "", "no_log": True},
276        "vdom": {"required": False, "type": "str", "default": "root"},
277        "https": {"required": False, "type": "bool", "default": True},
278        "ssl_verify": {"required": False, "type": "bool", "default": True},
279        "state": {"required": True, "type": "str",
280                  "choices": ["present", "absent"]},
281        "wireless_controller_hotspot20_anqp_network_auth_type": {
282            "required": False, "type": "dict", "default": None,
283            "options": {
284                "auth_type": {"required": False, "type": "str",
285                              "choices": ["acceptance-of-terms", "online-enrollment", "http-redirection",
286                                          "dns-redirection"]},
287                "name": {"required": True, "type": "str"},
288                "url": {"required": False, "type": "str"}
289
290            }
291        }
292    }
293
294    module = AnsibleModule(argument_spec=fields,
295                           supports_check_mode=False)
296
297    # legacy_mode refers to using fortiosapi instead of HTTPAPI
298    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
299                  'username' in module.params and module.params['username'] is not None and \
300                  'password' in module.params and module.params['password'] is not None
301
302    if not legacy_mode:
303        if module._socket_path:
304            connection = Connection(module._socket_path)
305            fos = FortiOSHandler(connection)
306
307            is_error, has_changed, result = fortios_wireless_controller_hotspot20(module.params, fos)
308        else:
309            module.fail_json(**FAIL_SOCKET_MSG)
310    else:
311        try:
312            from fortiosapi import FortiOSAPI
313        except ImportError:
314            module.fail_json(msg="fortiosapi module is required")
315
316        fos = FortiOSAPI()
317
318        login(module.params, fos)
319        is_error, has_changed, result = fortios_wireless_controller_hotspot20(module.params, fos)
320        fos.logout()
321
322    if not is_error:
323        module.exit_json(changed=has_changed, meta=result)
324    else:
325        module.fail_json(msg="Error in repo", meta=result)
326
327
328if __name__ == '__main__':
329    main()
330