Repository: ansible/ansible

Issue:
When using - gitlab_user_module - Auth token is not checked and error message is garbage
<!---
Verify first that your issue/request is not already reported on GitHub.
Also test if the latest release, and master branch are affected too.
-->

##### ISSUE TYPE
<!--- Pick one below and delete the rest: -->
 - Bug Report


##### COMPONENT NAME
<!--- Name of the module/plugin/task/feature -->
https://docs.ansible.com/ansible/gitlab_user_module.html

##### ANSIBLE VERSION
<!--- Paste verbatim output from “ansible --version” between quotes below -->
```
ansible 2.3.0.0
  config file = ./ansible.cfg
  configured module search path = [u'/usr/local/lib/python2.7/dist-packages/ara/plugins/modules']
  python version = 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609
```

##### CONFIGURATION
<!---
All default config
-->

##### OS / ENVIRONMENT
<!---
N/A
-->

##### SUMMARY
<!--- Explain the problem briefly -->
When using gitlab_user_module - module with an expired gitlab token, there is seemingly no check performed to see if the token exists or even has any permissions. As such when it gets to trying to creating a user it starts spewing python errors about data types rather than a real error message about the authentication token being bad. 

##### STEPS TO REPRODUCE
<!---
For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used.
-->

<!--- Paste example playbooks or commands between quotes below -->
```example.yaml

- hosts: host1
   gather_facts: no
   tasks:
     - name: Create Gitlab User
       gitlab_user:
         server_url: "https://{{ gitlab_url }}"
         validate_certs: false
         login_token: "{{ gitlab_token }}"
         name: "{{ etckeeper_username }}"
         username: "{{ etckeeper_username }}"
         password: "{{ etckeeper_password }}"
         email: blackhole@email.com
         group: "{{ group_name }}"
         sshkey_name: "etckeeper_key"
         sshkey_file: "{{ etckeeper_ssh-rsa_key }}"
         state: present
  delegate_to: localhost
 
```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
Error saying authentication token is expired or bad. 

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

<!--- Paste verbatim command output between quotes below -->
```
TASK [etckeeper_install : Create Gitlab User] *************************************************************************************************************************************
task path: /home/user/ansible_test/roles-dev/etckeeper_install/tasks/configure.yml:27
Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/source_control/gitlab_user.py
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: user
<localhost> EXEC /bin/sh -c 'sudo -H -S -n -u root /bin/sh -c '"'"'echo BECOME-SUCCESS-klqjckwtlzoeoaouulmnuumwdfbrsqdj; /usr/bin/python'"'"' && sleep 0'
fatal: [bios -> localhost]: FAILED! => {
    "changed": false,
    "failed": true,
    "module_stderr": "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n  InsecureRequestWarning)\nTraceback (most recent call last):\n  File \"/tmp/ansible_vIiKET/ansible_module_gitlab_user.py\", line 359, in <module>\n    main()\n  File \"/tmp/ansible_vIiKET/ansible_module_gitlab_user.py\", line 347, in main\n    if not user.existsUser(user_username) and state == \"absent\":\n  File \"/tmp/ansible_vIiKET/ansible_module_gitlab_user.py\", line 226, in existsUser\n    for user in found_user:\nTypeError: 'bool' object is not iterable\n",
    "module_stdout": "",
    "msg": "MODULE FAILURE",
    "rc": 1
}
```



Discussion:
cc @dj-wasabi
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->

Resolving patch:
diff --git a/lib/ansible/modules/source_control/gitlab_group.py b/lib/ansible/modules/source_control/gitlab_group.py
--- a/lib/ansible/modules/source_control/gitlab_group.py
+++ b/lib/ansible/modules/source_control/gitlab_group.py
@@ -165,7 +165,8 @@ def main():
     )
 
     if not HAS_GITLAB_PACKAGE:
-        module.fail_json(msg="Missing requried gitlab module (check docs or install with: pip install pyapi-gitlab")
+        module.fail_json(msg="Missing required gitlab module (check docs or "
+                             "install with: pip install pyapi-gitlab")
 
     server_url = module.params['server_url']
     verify_ssl = module.params['validate_certs']
@@ -200,6 +201,14 @@ def main():
         e = get_exception()
         module.fail_json(msg="Failed to connect to Gitlab server: %s " % e)
 
+    # Check if user is authorized or not before proceeding to any operations
+    # if not, exit from here
+    auth_msg = git.currentuser().get('message', None)
+    if auth_msg is not None and auth_msg == '401 Unauthorized':
+        module.fail_json(msg='User unauthorized',
+                         details="User is not allowed to access Gitlab server "
+                                 "using login_token. Please check login_token")
+
     # Validate if group exists and take action based on "state"
     group = GitLabGroup(module, git)
     group_name = group_name.lower()
diff --git a/lib/ansible/modules/source_control/gitlab_project.py b/lib/ansible/modules/source_control/gitlab_project.py
--- a/lib/ansible/modules/source_control/gitlab_project.py
+++ b/lib/ansible/modules/source_control/gitlab_project.py
@@ -375,6 +375,14 @@ def main():
         e = get_exception()
         module.fail_json(msg="Failed to connect to Gitlab server: %s " % e)
 
+    # Check if user is authorized or not before proceeding to any operations
+    # if not, exit from here
+    auth_msg = git.currentuser().get('message', None)
+    if auth_msg is not None and auth_msg == '401 Unauthorized':
+        module.fail_json(msg='User unauthorized',
+                         details="User is not allowed to access Gitlab server "
+                                 "using login_token. Please check login_token")
+
     # Validate if project exists and take action based on "state"
     project = GitLabProject(module, git)
     project_exists = project.existsProject(group_name, project_name)
diff --git a/lib/ansible/modules/source_control/gitlab_user.py b/lib/ansible/modules/source_control/gitlab_user.py
--- a/lib/ansible/modules/source_control/gitlab_user.py
+++ b/lib/ansible/modules/source_control/gitlab_user.py
@@ -340,6 +340,14 @@ def main():
         e = get_exception()
         module.fail_json(msg="Failed to connect to Gitlab server: %s " % e)
 
+    # Check if user is authorized or not before proceeding to any operations
+    # if not, exit from here
+    auth_msg = git.currentuser().get('message', None)
+    if auth_msg is not None and auth_msg == '401 Unauthorized':
+        module.fail_json(msg='User unauthorized',
+                         details="User is not allowed to access Gitlab server "
+                                 "using login_token. Please check login_token")
+
     # Validate if group exists and take action based on "state"
     user = GitLabUser(module, git)
 


Test patch: