
    Vh2;                         d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlmZmZ d dlmZmZ d dlmZmZ d d	lmZmZmZmZmZmZ d
 Zd Zd Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functionaz  
---
module: mongodb_user
short_description: Adds or removes a user from a MongoDB database
description:
    - Adds or removes a user from a MongoDB database.
version_added: "1.0.0"

extends_documentation_fragment:
  - community.mongodb.login_options
  - community.mongodb.ssl_options

options:
  replica_set:
    description:
      - Replica set to connect to (automatically connects to primary for writes).
    type: str
  database:
    description:
      - The name of the database to add/remove the user from.
    required: true
    type: str
    aliases: [db]
  name:
    description:
      - The name of the user to add or remove.
    required: true
    aliases: [user]
    type: str
  password:
    description:
      - The password to use for the user.
    type: str
    aliases: [pass]
  roles:
    type: list
    elements: raw
    description:
      - >
          The database user roles valid values could either be one or more of the following strings:
          'read', 'readWrite', 'dbAdmin', 'userAdmin', 'clusterAdmin', 'readAnyDatabase', 'readWriteAnyDatabase', 'userAdminAnyDatabase',
          'dbAdminAnyDatabase'
      - "Or the following dictionary '{ db: DATABASE_NAME, role: ROLE_NAME }'."
      - "This param requires pymongo 2.5+. If it is a string, mongodb 2.4+ is also required. If it is a dictionary, mongo 2.6+ is required."
  state:
    description:
      - The database user state.
    default: present
    choices: [absent, present]
    type: str
  update_password:
    default: always
    choices: [always, on_create]
    description:
      - C(always) will always update passwords and cause the module to return changed.
      - C(on_create) will only set the password for newly created users.
      - This must be C(always) to use the localhost exception when adding the first admin user.
      - This option is effectively ignored when using x.509 certs. It is defaulted to 'on_create' to maintain a           a specific module behaviour when the login_database is '$external'.
    type: str
  create_for_localhost_exception:
    type: path
    description:
      - This is parmeter is only useful for handling special treatment around the localhost exception.
      - If C(login_user) is defined, then the localhost exception is not active and this parameter has no effect.
      - If this file is NOT present (and C(login_user) is not defined), then touch this file after successfully adding the user.
      - If this file is present (and C(login_user) is not defined), then skip this task.

notes:
    - Requires the pymongo Python package on the remote host, version 4+. This
      can be installed using pip or the OS package manager. Newer mongo server versions require newer
      pymongo versions. @see https://www.mongodb.com/docs/languages/python/pymongo-driver/current/compatibility/
requirements:
  - "pymongo"
author:
    - "Elliott Foster (@elliotttf)"
    - "Julien Thebault (@Lujeni)"
a
  
- name: Create 'burgers' database user with name 'bob' and password '12345'.
  community.mongodb.mongodb_user:
    database: burgers
    name: bob
    password: 12345
    state: present

- name: Create a database user via SSL (MongoDB must be compiled with the SSL option and configured properly)
  community.mongodb.mongodb_user:
    database: burgers
    name: bob
    password: 12345
    state: present
    ssl: True

- name: Delete 'burgers' database user with name 'bob'.
  community.mongodb.mongodb_user:
    database: burgers
    name: bob
    state: absent

- name: Define more users with various specific roles (if not defined, no roles is assigned, and the user will be added via pre mongo 2.2 style)
  community.mongodb.mongodb_user:
    database: burgers
    name: ben
    password: 12345
    roles: read
    state: present

- name: Define roles
  community.mongodb.mongodb_user:
    database: burgers
    name: jim
    password: 12345
    roles: readWrite,dbAdmin,userAdmin
    state: present

- name: Define roles
  community.mongodb.mongodb_user:
    database: burgers
    name: joe
    password: 12345
    roles: readWriteAnyDatabase
    state: present

- name: Add a user to database in a replica set, the primary server is automatically discovered and written to
  community.mongodb.mongodb_user:
    database: burgers
    name: bob
    replica_set: belcher
    password: 12345
    roles: readWriteAnyDatabase
    state: present

# add a user 'oplog_reader' with read only access to the 'local' database on the replica_set 'belcher'. This is useful for oplog access (MONGO_OPLOG_URL).
# please notice the credentials must be added to the 'admin' database because the 'local' database is not synchronized and can't receive user credentials
# To login with such user, the connection string should be MONGO_OPLOG_URL="mongodb://oplog_reader:oplog_reader_password@server1,server2/local?authSource=admin"
# This syntax requires mongodb 2.6+ and pymongo 2.5+
- name: Roles as a dictionary
  community.mongodb.mongodb_user:
    login_user: root
    login_password: root_password
    database: admin
    user: oplog_reader
    password: oplog_reader_password
    state: present
    replica_set: belcher
    roles:
      - db: local
        role: read

- name: Adding a user with X.509 Member Authentication
  community.mongodb.mongodb_user:
    login_host: "mongodb-host.test"
    login_port: 27001
    login_database: "$external"
    database: "admin"
    name: "admin"
    password: "test"
    roles:
    - dbAdminAnyDatabase
    ssl: true
    ssl_ca_certs: "/tmp/ca.crt"
    ssl_certfile: "/tmp/tls.key" #cert and key in one file
    state: present
    auth_mechanism: "MONGODB-X509"
    connection_options:
     - "tlsAllowInvalidHostnames=true"
zc
user:
    description: The name of the user to add or remove.
    returned: success
    type: str
N)AnsibleModulemissing_required_lib)binary_type	text_type)	to_nativeto_bytes)r   mongodb_common_argument_spec
mongo_authPYMONGO_IMP_ERRpymongo_foundget_mongodb_clientc                     	 | |   j                  d      d   D ]   }|d   |k(  sd|vr|c S |d   |dfv s|c S  	 y	# t        $ r'}t        |d      r|j                  dk(  rn Y d}~y	d}~ww xY w)
zCheck if the user exists.

    Args:
        client (cursor): Mongodb cursor on admin database.
        user (str): User to check.
        db_name (str): User's database.

    Returns:
        dict: when user exists, False otherwise.
    	usersInfousersuserdbadmincode   NF)command	Exceptionhasattrr   )clientr   db_name
mongo_userexceps        r/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/mongodb/plugins/modules/mongodb_user.py	user_findr!      s     /11+>wG 	&J&!T)z)%% d#'99%%	&   5&!ejjB&6  s%   "> > 	> > > 	A.A))A.c                     ||   }	 t        |||      }|rd}	nd}	i }
|||
d<   |||
d<    |j                  |	|fi |
 y # t        $ r)}t        |d      r|j                  dk(  rd}n Y d }~Yd }~ww xY w)Nr      F
updateUser
createUserpwdroles)r!   r   r   r   r   )moduler   r   r   passwordr'   r   existsr   user_add_db_command	user_dicts              r    user_addr-      s     
B
641 **I#	%"	'BJJ"D6I6-  
 5&!ejjB&6F s   A   	A2	A--A2c                     t        |||      }|r7| j                  r| j                  d|       ||   }|j                  d|       y | j                  d|       y )NTchangedr   dropUserF)r!   
check_mode	exit_jsonr   )r(   r   r   r   r*   r   s         r    user_remover4     sY    vtW-FT5G_


:t$T2    c                 |    d } |||      }| j                  dg       }t        |d       t        |d       k(  ryy)Nc                     t               }| D ]@  }t        |t        t        f      r||d}|j	                  |       0|j	                  |       B |S )N)roler   )list
isinstancer   r	   append)r'   r   outputr8   new_roles        r    "make_sure_roles_are_a_list_of_dictzBcheck_if_roles_changed.<locals>.make_sure_roles_are_a_list_of_dict(  sP     	$D$i 89$(8h'd#	$ r5   r'   c                 4    t        | j                               S Nsorteditemsr'   s    r    <lambda>z(check_if_roles_changed.<locals>.<lambda>5  s    vekkm7L r5   )keyc                 4    t        | j                               S r@   rA   rD   s    r    rE   z(check_if_roles_changed.<locals>.<lambda>5  s*    w}  D  J  J  L  xM r5   FT)getrB   )uinfor'   r   r>   roles_as_list_of_dictuinfo_roless         r    check_if_roles_changedrL     sR    " ?ugN))GR(K#)LMQWXc  jM  RN  Nr5   c                     t               } | j                  t        ddg      t        ddg      t        dgd      t        d       t        d dd	
      t        dddg      t        dddgd      t        d d             t        | d      }|j                  d   }|j                  d   dk(  rd|j                  d<   t
        s |j                  t        d      t               |j                  d   }|t        |d      nd }|j                  d   }|j                  d    }|j                  d!   }|j                  d"   xs g }|j                  d#   }	|j                  d   }
	 d}|j                  d$   d}t        ||%      }t        |||%      }|	dk(  r||
dk(  r|j                  d('       |G|Et        j                  j!                  |      r&	 j#                          |j%                  d|dd)*       	 |
dk7  r1t'        ||      }|r"d }t)        |||      s|j%                  d|+       |j*                  r|j%                  d|+       t-        |||||       	 j#                          |C|A	 t3        |d-      j#                          n%|	dk(  r 	 t5        |||       	 j#                          |j%                  d|+       y # t        $ r)}|j                  d&t        |      z  '       Y d }~dd }~ww xY w# t        $ r Y &w xY w# t        $ r;}|j                  d,t        |      z  t/        j0                                Y d }~d }~ww xY w# t        $ r Y w xY w# 	 j#                          w # t        $ r Y w w xY wxY w# t        $ r@}|j                  dd.|d/t        |      t/        j0                         0       Y d }~d }~ww xY w# t        $ r<}|j                  d1t        |      z  t/        j0                                Y d }~qd }~ww xY w# t        $ r Y tw xY w# 	 j#                          w # t        $ r Y w w xY wxY w)2NTr   )requiredaliasesr   pass)rO   no_log)defaultr9   raw)rR   typeelementspresentabsent)rR   choicesalways	on_createF)rR   rX   rQ   path)rR   rT   )databasenamer)   replica_setr'   stateupdate_passwordcreate_for_localhost_exception)argument_specsupports_check_mode
login_userlogin_databasez	$externalr`   pymongo)msg	exceptionra   surrogate_or_strict)errorsr\   r]   r)   r'   r_   r^   )directConnectionz!Unable to connect to database: %s)rg   zYpassword parameter required when adding a user unless update_password is set to on_createz2The path in create_for_localhost_exception exists.)r0   r   skippedrg   r/   z Unable to add or update user: %swbzCAdded user but unable to touch create_for_localhost_exception file z: )r0   rg   rh   zUnable to remove user: %s)r   updatedictr   paramsr   	fail_jsonr   r   r   r   r   r   r
   osr[   r*   closer3   r!   rL   r2   r-   	traceback
format_excopenr4   )rb   r(   rd   ra    b_create_for_localhost_exceptionr   r   r)   r'   r_   r`   rk   r   erI   s                  r    mainry   >  s   02MtdV44&2vht4&4fu=9x.CDX+7NW\]'+Dv'F  	 # F |,J }}%&+5+6'(1)<#2 	 	4 &,]]3S%T" *5 	/8MN;? %
 mmJ'G== D}}Z(HMM'"(bEMM'"Emm$56OQ =='/##F=MNFF=MN 	8 ;!|}"@"Lww~~>?LLN   T4  NB   C	(*!&$8#H1%H((T(B    D 9VVWdHeD "@"L5t<BBD 
(		6 T-y  Q@9Q<OPPQ !   	v!CiPQl!R^g^r^r^tuu	v
         hF  HQ  RS  HT  U'224 !    	o!<y|!KW`WkWkWmnn	o
   s  &.K L  <A%L "M 7N O 'P 	K=K88K= 	LL	M1M
M& MM& 	M#"M#&N(M98N9	NNNN	O5OO	P 1PP/ PP/ 	P,+P,/Q1QQ	QQQQ__main__) 
__future__r   r   r   rT   __metaclass__DOCUMENTATIONEXAMPLESRETURNrr   rt   ansible.module_utils.basicr   r   ansible.module_utils.sixr   r	   ansible.module_utils._textr
   r   Iansible_collections.community.mongodb.plugins.module_utils.mongodb_commonr   r   r   r   r   r!   r-   r4   rL   ry   __name__ r5   r    <module>r      s{    A @M^Yv
 
  K ; : :7@3 Ni.X zF r5   