├── .gitignore ├── .idea ├── encodings.xml ├── misc.xml ├── modules.xml ├── odoo-dingtalk-connector.iml └── vcs.xml ├── LICENSE ├── README.md ├── __init__.py ├── __manifest__.py ├── controllers ├── __init__.py └── main.py ├── dingtalk ├── __init__.py ├── crypto.py └── main.py ├── docs ├── CHANGELOG.md ├── files │ └── http.py └── img │ └── donation.png ├── models ├── __init__.py ├── hr_department.py ├── res_config_settings.py └── res_users.py ├── static └── description │ └── icon.png └── views ├── dingtalk_connector_templates.xml └── res_config_settings_view.xml /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/odoo-dingtalk-connector.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 11 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OdooDingtalkConnector 2 | Odoo钉钉连接器 3 | 4 | ## 简介 5 | Odoo连接器提供Odoo与钉钉的集成服务,基于Odoo12.0开发。 6 | 7 | ## [更新日志](./docs/CHANGELOG.md) 8 | 版本:12.0.1.5 (2019-03-19 更新) 9 | 10 | ## 说明 11 | 该项目仍在Build阶段,目前可以正常使用的功能: 12 | - 免登 13 | - 手动同步钉钉部门与员工 14 | - 业务回调接口 15 | > 其中`业务回调接口`功能业务上只完成了接口的注册部分,在基本功能上,消息体的加密解密已完成,如果急需使用的`业务回调接口`功能的话可以尝试自行编写数据接收业务。我也会加快开发进度,完成一些基本的回调同步业务。 16 | 17 | ## 额外使用的第三方Python库 18 | - pycryptodome 19 | 20 | ## 安装步骤 21 | 1. 安装模块依赖的第三方Python库 22 | 2. 将`/docs/files/http.py`覆盖`odoo-root/odoo/http.py`,其中`odoo-root`表示odoo的根目录 23 | 3. 在odoo中安装模块 24 | 25 | ## 捐赠 26 | 27 | 如果你觉得这个项目很赞且对你有帮助的话,请我喝一杯咖啡呗:) 28 | ![捐赠二维码](./docs/img/donation.png) 29 | 30 | ## License 31 | 32 | [GNU General Public License v3.0](./LICENSE) -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from . import dingtalk, models, controllers 3 | -------------------------------------------------------------------------------- /__manifest__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | { 3 | 'name': "钉钉", 4 | 'summary': """提供钉钉集成服务""", 5 | 'description': """ 6 | 提供钉钉集成服务 7 | """, 8 | 'author': "Li jinhui", 9 | 'website': "https://ocubexo.github.io", 10 | 'category': 'Connector', 11 | 'version': '1.5', 12 | 'depends': ['hr'], 13 | 'external_dependencies': { 14 | 'python': ['pycryptodome'] 15 | }, 16 | 'data': [ 17 | 'views/dingtalk_connector_templates.xml', 18 | 'views/res_config_settings_view.xml' 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /controllers/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from . import main 3 | -------------------------------------------------------------------------------- /controllers/main.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import time, random 3 | from odoo.addons.dingtalk_connector.dingtalk.main import DingTalk 4 | from odoo.addons.dingtalk_connector.dingtalk.crypto import DingTalkCrypto 5 | from odoo import http 6 | from odoo.http import request 7 | 8 | 9 | class IndexController(http.Controller): 10 | BASE_URL = '/dingtalk' 11 | 12 | def get_dingtalk(self): 13 | """ 14 | 获取钉钉API服务 15 | """ 16 | # 获取配置信息 17 | config = request.env['ir.config_parameter'].sudo() 18 | # 返回钉钉API服务 19 | return DingTalk(config.get_param('dingtalk_app_key'), config.get_param('dingtalk_app_secret'), 20 | config.get_param('dingtalk_sns_app_id'), config.get_param('dingtalk_sns_app_secret')) 21 | 22 | @http.route(BASE_URL + '/sign/in', type='http', auth='none') 23 | def sign_in(self, **kw): 24 | """ 25 | 钉钉免登入口 26 | """ 27 | config = request.env['ir.config_parameter'].sudo() 28 | data = { 29 | 'corp_id': config.get_param('dingtalk_corp_id') 30 | } 31 | return request.render('dingtalk_connector.sign_in', data) 32 | 33 | @http.route(BASE_URL + '/auth', type='http', auth='none') 34 | def auth(self, **kw): 35 | """ 36 | 钉钉免登认证 37 | """ 38 | authCode = kw.get('authCode') 39 | code = kw.get('code') 40 | dingtalk = self.get_dingtalk() 41 | # 检测是通过扫码跳转还是免登跳转 42 | if authCode: 43 | # 免登跳转处理 44 | try: 45 | user_info = dingtalk.get_user_info_by_auth_code(authCode) 46 | user_id = user_info.get('userid') 47 | except: 48 | return http.local_redirect('/web/login') 49 | elif code: 50 | # 扫码跳转处理 51 | try: 52 | persistent_code_data = dingtalk.get_sns_persistent_code(code) 53 | unionid = persistent_code_data.get('unionid') 54 | user_id = dingtalk.get_user_id_by_unionid(unionid).get('userid') 55 | except: 56 | return http.local_redirect('/web/login') 57 | # 检查钉钉用户是否存在 58 | if user_id: 59 | # 根据钉钉Id判断Odoo用户是否存在,存在即登陆 60 | user = request.env['res.users'].sudo().search([('dingtalk_id', '=', user_id)]) 61 | if user: 62 | # 添加登陆模式为钉钉免登模式 63 | request.session.dingtalk_auth = True 64 | # 生成登陆凭证 65 | request.session.authenticate(request.session.db, user.login, user_id) 66 | return http.local_redirect('/web') 67 | else: 68 | # 自动注册 69 | password = 'dingtalk_id:' + user_id + '|key:' + str(random.randint(100000, 999999)) 70 | fail = request.env['res.users'].sudo().create_user_by_dingtalk_id(user_id, password) 71 | if not fail: 72 | return http.local_redirect('/dingtalk/sign/in') 73 | return http.local_redirect('/web/login') 74 | 75 | @http.route(BASE_URL + '/call_back', type='json', auth='none', methods=['POST'], csrf=False) 76 | def delete_user(self, **kw): 77 | """ 78 | 钉钉业务回调 接收接口 79 | """ 80 | 81 | # TODO 接收业务回调数据 82 | def result(): 83 | # 获取Odoo配置 84 | config = request.env['ir.config_parameter'].sudo() 85 | dingtalkCrypto = DingTalkCrypto(config.get_param('dingtalk_call_back_api_aes_key'), 86 | config.get_param('dingtalk_corp_id')) 87 | # 加密数据 88 | encrypt = dingtalkCrypto.encrypt('success') 89 | # 获取当前时间戳 90 | timestamp = str(int(round(time.time() * 1000))) 91 | # 获取随机字符串 92 | nonce = dingtalkCrypto.generateRandomKey(8) 93 | # 生成签名 94 | signature = dingtalkCrypto.generateSignature(nonce, timestamp, 95 | config.get_param('dingtalk_call_back_api_token'), 96 | encrypt) 97 | data = { 98 | 'msg_signature': signature, 99 | 'timeStamp': timestamp, 100 | 'nonce': nonce, 101 | 'encrypt': encrypt 102 | } 103 | result = { 104 | 'json': True, 105 | 'data': data 106 | } 107 | return result 108 | 109 | return result() 110 | 111 | @http.route(BASE_URL + '/qrcode', type='http', auth='none') 112 | def qrcode(self, **kw): 113 | """ 114 | 钉钉扫码登陆页面 115 | """ 116 | config = request.env['ir.config_parameter'].sudo() 117 | data = { 118 | 'app_id': config.get_param('dingtalk_sns_app_id'), 119 | 'redirect_url': request.httprequest.host_url + 'dingtalk/auth' 120 | } 121 | return request.render('dingtalk_connector.qrcode_login', data) 122 | -------------------------------------------------------------------------------- /dingtalk/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from . import main, crypto 3 | -------------------------------------------------------------------------------- /dingtalk/crypto.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | import io, base64, binascii, hashlib, string, struct 3 | from random import choice 4 | from Crypto.Cipher import AES 5 | 6 | 7 | class DingTalkCrypto: 8 | def __init__(self, encodingAesKey, key): 9 | self.encodingAesKey = encodingAesKey 10 | self.key = key 11 | self.aesKey = base64.b64decode(self.encodingAesKey + '=') 12 | 13 | def encrypt(self, content): 14 | """ 15 | 加密 16 | """ 17 | msg_len = self.length(content) 18 | content = self.generateRandomKey(16) + msg_len.decode() + content + self.key 19 | contentEncode = self.pks7encode(content) 20 | iv = self.aesKey[:16] 21 | aesEncode = AES.new(self.aesKey, AES.MODE_CBC, iv) 22 | aesEncrypt = aesEncode.encrypt(contentEncode) 23 | return base64.b64encode(aesEncrypt).decode().replace('\n', '') 24 | 25 | def length(self, content): 26 | """ 27 | 将msg_len转为符合要求的四位字节长度 28 | """ 29 | l = len(content) 30 | return struct.pack('>l', l) 31 | 32 | def pks7encode(self, content): 33 | """ 34 | 安装 PKCS#7 标准填充字符串 35 | """ 36 | l = len(content) 37 | output = io.StringIO() 38 | val = 32 - (l % 32) 39 | for _ in xrange(val): 40 | output.write('%02x' % val) 41 | return bytes(content, 'utf-8') + binascii.unhexlify(output.getvalue()) 42 | 43 | def pks7decode(self, content): 44 | nl = len(content) 45 | val = int(binascii.hexlify(content[-1]), 16) 46 | if val > 32: 47 | raise ValueError('Input is not padded or padding is corrupt') 48 | l = nl - val 49 | return content[:l] 50 | 51 | def decrypt(self, content): 52 | """ 53 | 解密数据 54 | """ 55 | # 钉钉返回的消息体 56 | content = base64.decode(content) 57 | iv = self.aesKey[:16] ##初始向量 58 | aesDecode = AES.new(self.aesKey, AES.MODE_CBC, iv) 59 | decodeRes = aesDecode.decrypt(content)[20:].replace(self.key, '') 60 | # 获取去除初始向量,四位msg长度以及尾部corpid 61 | return self.pks7decode(decodeRes) 62 | 63 | def generateRandomKey(self, size, 64 | chars=string.ascii_letters + string.ascii_lowercase + string.ascii_uppercase + string.digits): 65 | """ 66 | 生成加密所需要的随机字符串 67 | """ 68 | return ''.join(choice(chars) for i in range(size)) 69 | 70 | def generateSignature(self, nonce, timestamp, token, msg_encrypt): 71 | """ 72 | 生成签名 73 | """ 74 | signList = ''.join(sorted([nonce, timestamp, token, msg_encrypt])).encode() 75 | return hashlib.sha1(signList).hexdigest() -------------------------------------------------------------------------------- /dingtalk/main.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import requests, json, time 3 | 4 | 5 | class DingTalk: 6 | def __init__(self, app_key=None, app_secret=None, sns_app_id=None, sns_app_secret=None): 7 | self.app_key = app_key 8 | self.app_secret = app_secret 9 | self.sns_app_id = sns_app_id 10 | self.sns_app_secret = sns_app_secret 11 | 12 | def send_request(self, method, request_url, data, retry=True, retry_count=0, retry_interval=3): 13 | """ 14 | 发送HTTP请求 15 | """ 16 | headers = { 17 | 'Content-Type': 'application/json;charset=utf-8' 18 | } 19 | if method == 'GET': 20 | res = requests.get(request_url, params=data, headers=headers, verify=False) 21 | if method == 'POST': 22 | res = requests.post(request_url, data=json.dumps(data), headers=headers, verify=False) 23 | result = res.json() 24 | if result.get('errcode') != 0: 25 | if retry: 26 | if retry_count <= 5: 27 | # 接口访问出错时重试 28 | time.sleep(retry_interval) 29 | return self.send_request(method, request_url, data, retry_count=retry_count + 1) 30 | else: 31 | raise Exception('(钉钉接口错误)' + result.get('errmsg') + ' | (接口地址)' + request_url) 32 | else: 33 | raise Exception('(钉钉接口错误)' + result.get('errmsg') + ' | (接口地址)' + request_url) 34 | else: 35 | return result 36 | 37 | def get_access_token_data(self): 38 | """ 39 | 获取AccessToken数据 40 | """ 41 | method = 'GET' 42 | url = 'https://oapi.dingtalk.com/gettoken' 43 | params = { 44 | 'appkey': self.app_key, 45 | 'appsecret': self.app_secret 46 | } 47 | result = self.send_request(method, url, params) 48 | return result 49 | 50 | def get_access_token(self): 51 | """ 52 | 获取AccessToken 53 | """ 54 | return self.get_access_token_data().get('access_token') 55 | 56 | def get_access_token_param(self): 57 | """ 58 | 获取AccessToken Get参数 59 | """ 60 | return '?access_token=' + self.get_access_token_data().get('access_token') 61 | 62 | def get_user_info_by_id(self, user_id): 63 | """ 64 | 通过UserId获取用户基本信息 65 | """ 66 | method = 'GET' 67 | url = 'https://oapi.dingtalk.com/user/get' 68 | params = { 69 | 'access_token': self.get_access_token(), 70 | 'userid': user_id 71 | } 72 | result = self.send_request(method, url, params) 73 | return result 74 | 75 | def get_user_detail_by_ids(self, user_ids): 76 | """ 77 | 通过一组UserId获取一组用户的详细信息 78 | """ 79 | method = 'POST' 80 | url = 'https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/list' + self.get_access_token_param() 81 | data = { 82 | 'userid_list': user_ids, 83 | 'field_filter_list': "sys00-name,sys00-email,sys00-dept,sys00-mainDept,sys00-mobile", 84 | } 85 | result = self.send_request(method, url, data) 86 | return result 87 | 88 | def get_user_info_by_auth_code(self, auth_code): 89 | """ 90 | 通过AuthCode获取用户基本信息 91 | """ 92 | method = 'GET' 93 | url = 'https://oapi.dingtalk.com/user/getuserinfo' 94 | params = { 95 | 'access_token': self.get_access_token(), 96 | 'code': auth_code 97 | } 98 | result = self.send_request(method, url, params) 99 | return result 100 | 101 | def get_sns_access_token_data(self): 102 | """ 103 | 获取SNSAccessToken 104 | """ 105 | method = 'GET' 106 | url = 'https://oapi.dingtalk.com/sns/gettoken' 107 | params = { 108 | 'appid': self.sns_app_id, 109 | 'appsecret': self.sns_app_secret 110 | } 111 | result = self.send_request(method, url, params) 112 | return result 113 | 114 | def get_sns_access_token(self): 115 | return self.get_sns_access_token_data().get('access_token') 116 | 117 | def get_sns_access_token_param(self): 118 | return '?access_token=' + self.get_sns_access_token() 119 | 120 | def get_sns_persistent_code(self, code): 121 | """ 122 | 获取SNSPersistentCode 123 | """ 124 | method = 'POST' 125 | url = 'https://oapi.dingtalk.com/sns/get_persistent_code' + self.get_sns_access_token_param() 126 | data = { 127 | 'tmp_auth_code': code 128 | } 129 | result = self.send_request(method, url, data) 130 | return result 131 | 132 | def get_sns_token(self, openid, persistent_code): 133 | """ 134 | 获取SNSToken 135 | """ 136 | method = 'POST' 137 | url = 'https://oapi.dingtalk.com/sns/get_sns_token' + self.get_sns_access_token_param() 138 | data = { 139 | 'openid': openid, 140 | 'persistent_code': persistent_code 141 | } 142 | result = self.send_request(method, url, data) 143 | return result 144 | 145 | def get_sns_user_info(self, sns_token): 146 | """ 147 | 获取SNSUserInfo 148 | """ 149 | method = 'GET' 150 | url = 'https://oapi.dingtalk.com/sns/getuserinfo' 151 | params = { 152 | 'sns_token': sns_token, 153 | } 154 | result = self.send_request(method, url, params) 155 | return result 156 | 157 | def get_user_id_by_unionid(self, unionid): 158 | """ 159 | 通过UnionId获取UserId 160 | """ 161 | method = 'GET' 162 | url = 'https://oapi.dingtalk.com/user/getUseridByUnionid' 163 | params = { 164 | 'access_token': self.get_access_token(), 165 | 'unionid': unionid 166 | } 167 | result = self.send_request(method, url, params) 168 | return result 169 | 170 | def get_user_id_list_by_paging(self, offset): 171 | """ 172 | 分页获取在职用户Id列表 173 | """ 174 | method = 'POST' 175 | url = 'https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob' + self.get_access_token_param() 176 | data = { 177 | 'status_list': '2,3', 178 | 'offset': offset, 179 | 'size': 20 180 | } 181 | result = self.send_request(method, url, data) 182 | return result 183 | 184 | def get_user_id_list(self): 185 | """ 186 | 获取所有在职用户Id 187 | """ 188 | offset = 0 189 | userid_list = [] 190 | # 循环分页获取所有UserId 191 | while True: 192 | result = self.get_user_id_list_by_paging(offset).get('result') 193 | userid_list.extend(result.get('data_list')) 194 | # 检测分页是否结束 195 | if result.get('next_cursor') != None: 196 | offset = result.get('next_cursor') 197 | else: 198 | break 199 | return userid_list 200 | 201 | def get_dimission_user_id_list_by_paging(self, offset, retry=False): 202 | """ 203 | 分页获取离职用户Id列表 204 | """ 205 | method = 'POST' 206 | url = 'https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission' + self.get_access_token_param() 207 | data = { 208 | 'offset': offset, 209 | 'size': 20 210 | } 211 | result = self.send_request(method, url, data) 212 | return result 213 | 214 | def get_dimission_user_id_list(self): 215 | """ 216 | 获取所有离职用户Id 217 | """ 218 | offset = 0 219 | userid_list = [] 220 | # 循环分页获取所有UserId 221 | while True: 222 | result = self.get_dimission_user_id_list_by_paging(offset).get('result') 223 | userid_list.extend(result.get('data_list')) 224 | # 检测分页是否结束 225 | if result.get('next_cursor') != None: 226 | offset = result.get('next_cursor') 227 | else: 228 | break 229 | return userid_list 230 | 231 | def callback_api_register(self, call_back_tag, token, aes_key, call_back_url): 232 | """ 233 | 业务回调接口 注册接口 234 | """ 235 | method = 'POST' 236 | url = 'https://oapi.dingtalk.com/call_back/register_call_back' + self.get_access_token_param() 237 | data = { 238 | 'call_back_tag': call_back_tag, 239 | 'token': token, 240 | 'aes_key': aes_key, 241 | 'url': call_back_url 242 | } 243 | result = self.send_request(method, url, data) 244 | return result 245 | 246 | def get_departments(self, id, fetch_child=False): 247 | """ 248 | 根据Id获取部门列表 249 | """ 250 | method = 'GET' 251 | url = 'https://oapi.dingtalk.com/department/list' 252 | params = { 253 | 'access_token': self.get_access_token(), 254 | 'id': id, 255 | 'fetch_child': fetch_child 256 | } 257 | result = self.send_request(method, url, params) 258 | return result 259 | 260 | def get_department_info(self, id): 261 | """ 262 | 根据Id获取部门信息 263 | """ 264 | method = 'GET' 265 | url = 'https://oapi.dingtalk.com/department/get' 266 | params = { 267 | 'access_token': self.get_access_token(), 268 | 'id': id 269 | } 270 | result = self.send_request(method, url, params) 271 | return result 272 | -------------------------------------------------------------------------------- /docs/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 更新日志 2 | 3 | ## 1.1 (20190118) 4 | 1. 修复钉钉模块SDK引入报错问题。(问题原因:odoo引入模块本地第三方包时,需要加上odoo.addons.模块名的命名空间。) 5 | 6 | ## 1.5 (20190319) 7 | 1. 增加扫码登陆功能。 8 | 2. 完善手工同步。 9 | 3. 修复遗留BUG。 -------------------------------------------------------------------------------- /docs/files/http.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | #---------------------------------------------------------- 3 | # OpenERP HTTP layer 4 | #---------------------------------------------------------- 5 | import ast 6 | import collections 7 | import contextlib 8 | import datetime 9 | import functools 10 | import hashlib 11 | import hmac 12 | import inspect 13 | import logging 14 | import mimetypes 15 | import os 16 | import pprint 17 | import random 18 | import re 19 | import sys 20 | import threading 21 | import time 22 | import traceback 23 | import warnings 24 | from os.path import join as opj 25 | from zlib import adler32 26 | 27 | import babel.core 28 | from datetime import datetime, date 29 | import passlib.utils 30 | import psycopg2 31 | import json 32 | import werkzeug.contrib.sessions 33 | import werkzeug.datastructures 34 | import werkzeug.exceptions 35 | import werkzeug.local 36 | import werkzeug.routing 37 | import werkzeug.wrappers 38 | import werkzeug.wsgi 39 | from werkzeug import urls 40 | from werkzeug.wsgi import wrap_file 41 | 42 | try: 43 | import psutil 44 | except ImportError: 45 | psutil = None 46 | 47 | import odoo 48 | from odoo import fields 49 | from .service.server import memory_info 50 | from .service import security, model as service_model 51 | from .tools.func import lazy_property 52 | from .tools import ustr, consteq, frozendict, pycompat, unique, date_utils 53 | 54 | from .modules.module import module_manifest 55 | 56 | _logger = logging.getLogger(__name__) 57 | rpc_request = logging.getLogger(__name__ + '.rpc.request') 58 | rpc_response = logging.getLogger(__name__ + '.rpc.response') 59 | 60 | # 1 week cache for statics as advised by Google Page Speed 61 | STATIC_CACHE = 60 * 60 * 24 * 7 62 | 63 | # To remove when corrected in Babel 64 | babel.core.LOCALE_ALIASES['nb'] = 'nb_NO' 65 | 66 | #---------------------------------------------------------- 67 | # RequestHandler 68 | #---------------------------------------------------------- 69 | # Thread local global request object 70 | _request_stack = werkzeug.local.LocalStack() 71 | 72 | request = _request_stack() 73 | """ 74 | A global proxy that always redirect to the current request object. 75 | """ 76 | 77 | def replace_request_password(args): 78 | # password is always 3rd argument in a request, we replace it in RPC logs 79 | # so it's easier to forward logs for diagnostics/debugging purposes... 80 | if len(args) > 2: 81 | args = list(args) 82 | args[2] = '*' 83 | return tuple(args) 84 | 85 | # don't trigger debugger for those exceptions, they carry user-facing warnings 86 | # and indications, they're not necessarily indicative of anything being 87 | # *broken* 88 | NO_POSTMORTEM = (odoo.osv.orm.except_orm, 89 | odoo.exceptions.AccessError, 90 | odoo.exceptions.ValidationError, 91 | odoo.exceptions.MissingError, 92 | odoo.exceptions.AccessDenied, 93 | odoo.exceptions.Warning, 94 | odoo.exceptions.RedirectWarning) 95 | def dispatch_rpc(service_name, method, params): 96 | """ Handle a RPC call. 97 | 98 | This is pure Python code, the actual marshalling (from/to XML-RPC) is done 99 | in a upper layer. 100 | """ 101 | try: 102 | rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG) 103 | rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG) 104 | if rpc_request_flag or rpc_response_flag: 105 | start_time = time.time() 106 | start_memory = 0 107 | if psutil: 108 | start_memory = memory_info(psutil.Process(os.getpid())) 109 | if rpc_request and rpc_response_flag: 110 | odoo.netsvc.log(rpc_request, logging.DEBUG, '%s.%s' % (service_name, method), replace_request_password(params)) 111 | 112 | threading.current_thread().uid = None 113 | threading.current_thread().dbname = None 114 | if service_name == 'common': 115 | dispatch = odoo.service.common.dispatch 116 | elif service_name == 'db': 117 | dispatch = odoo.service.db.dispatch 118 | elif service_name == 'object': 119 | dispatch = odoo.service.model.dispatch 120 | result = dispatch(method, params) 121 | 122 | if rpc_request_flag or rpc_response_flag: 123 | end_time = time.time() 124 | end_memory = 0 125 | if psutil: 126 | end_memory = memory_info(psutil.Process(os.getpid())) 127 | logline = '%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (service_name, method, end_time - start_time, start_memory / 1024, end_memory / 1024, (end_memory - start_memory)/1024) 128 | if rpc_response_flag: 129 | odoo.netsvc.log(rpc_response, logging.DEBUG, logline, result) 130 | else: 131 | odoo.netsvc.log(rpc_request, logging.DEBUG, logline, replace_request_password(params), depth=1) 132 | 133 | return result 134 | except NO_POSTMORTEM: 135 | raise 136 | except odoo.exceptions.DeferredException as e: 137 | _logger.exception(odoo.tools.exception_to_unicode(e)) 138 | odoo.tools.debugger.post_mortem(odoo.tools.config, e.traceback) 139 | raise 140 | except Exception as e: 141 | _logger.exception(odoo.tools.exception_to_unicode(e)) 142 | odoo.tools.debugger.post_mortem(odoo.tools.config, sys.exc_info()) 143 | raise 144 | 145 | def local_redirect(path, query=None, keep_hash=False, forward_debug=True, code=303): 146 | url = path 147 | if not query: 148 | query = {} 149 | if request and request.debug: 150 | if forward_debug: 151 | query['debug'] = '' 152 | else: 153 | query['debug'] = None 154 | if query: 155 | url += '?' + werkzeug.url_encode(query) 156 | if keep_hash: 157 | return redirect_with_hash(url, code) 158 | else: 159 | return werkzeug.utils.redirect(url, code) 160 | 161 | def redirect_with_hash(url, code=303): 162 | # Most IE and Safari versions decided not to preserve location.hash upon 163 | # redirect. And even if IE10 pretends to support it, it still fails 164 | # inexplicably in case of multiple redirects (and we do have some). 165 | # See extensive test page at http://greenbytes.de/tech/tc/httpredirects/ 166 | if request.httprequest.user_agent.browser in ('firefox',): 167 | return werkzeug.utils.redirect(url, code) 168 | # FIXME: decide whether urls should be bytes or text, apparently 169 | # addons/website/controllers/main.py:91 calls this with a bytes url 170 | # but addons/web/controllers/main.py:481 uses text... (blows up on login) 171 | url = pycompat.to_text(url).strip() 172 | if urls.url_parse(url, scheme='http').scheme not in ('http', 'https'): 173 | url = u'http://' + url 174 | url = url.replace("'", "%27").replace("<", "%3C") 175 | return "" % url 176 | 177 | class WebRequest(object): 178 | """ Parent class for all Odoo Web request types, mostly deals with 179 | initialization and setup of the request object (the dispatching itself has 180 | to be handled by the subclasses) 181 | 182 | :param httprequest: a wrapped werkzeug Request object 183 | :type httprequest: :class:`werkzeug.wrappers.BaseRequest` 184 | 185 | .. attribute:: httprequest 186 | 187 | the original :class:`werkzeug.wrappers.Request` object provided to the 188 | request 189 | 190 | .. attribute:: params 191 | 192 | :class:`~collections.Mapping` of request parameters, not generally 193 | useful as they're provided directly to the handler method as keyword 194 | arguments 195 | """ 196 | def __init__(self, httprequest): 197 | self.httprequest = httprequest 198 | self.httpresponse = None 199 | self.disable_db = False 200 | self.endpoint = None 201 | self.endpoint_arguments = None 202 | self.auth_method = None 203 | self._cr = None 204 | self._uid = None 205 | self._context = None 206 | self._env = None 207 | 208 | # prevents transaction commit, use when you catch an exception during handling 209 | self._failed = None 210 | 211 | # set db/uid trackers - they're cleaned up at the WSGI 212 | # dispatching phase in odoo.service.wsgi_server.application 213 | if self.db: 214 | threading.current_thread().dbname = self.db 215 | if self.session.uid: 216 | threading.current_thread().uid = self.session.uid 217 | 218 | @property 219 | def cr(self): 220 | """ :class:`~odoo.sql_db.Cursor` initialized for the current method call. 221 | 222 | Accessing the cursor when the current request uses the ``none`` 223 | authentication will raise an exception. 224 | """ 225 | # can not be a lazy_property because manual rollback in _call_function 226 | # if already set (?) 227 | if not self.db: 228 | raise RuntimeError('request not bound to a database') 229 | if not self._cr: 230 | self._cr = self.registry.cursor() 231 | return self._cr 232 | 233 | @property 234 | def uid(self): 235 | return self._uid 236 | 237 | @uid.setter 238 | def uid(self, val): 239 | self._uid = val 240 | self._env = None 241 | 242 | @property 243 | def context(self): 244 | """ :class:`~collections.Mapping` of context values for the current request """ 245 | if self._context is None: 246 | self._context = frozendict(self.session.context) 247 | return self._context 248 | 249 | @context.setter 250 | def context(self, val): 251 | self._context = frozendict(val) 252 | self._env = None 253 | 254 | @property 255 | def env(self): 256 | """ The :class:`~odoo.api.Environment` bound to current request. """ 257 | if self._env is None: 258 | self._env = odoo.api.Environment(self.cr, self.uid, self.context) 259 | return self._env 260 | 261 | @lazy_property 262 | def lang(self): 263 | context = dict(self.context) 264 | self.session._fix_lang(context) 265 | self.context = context 266 | return context["lang"] 267 | 268 | @lazy_property 269 | def session(self): 270 | """ :class:`OpenERPSession` holding the HTTP session data for the 271 | current http session 272 | """ 273 | return self.httprequest.session 274 | 275 | def __enter__(self): 276 | _request_stack.push(self) 277 | return self 278 | 279 | def __exit__(self, exc_type, exc_value, traceback): 280 | _request_stack.pop() 281 | 282 | if self._cr: 283 | if exc_type is None and not self._failed: 284 | self._cr.commit() 285 | if self.registry: 286 | self.registry.signal_changes() 287 | elif self.registry: 288 | self.registry.reset_changes() 289 | self._cr.close() 290 | # just to be sure no one tries to re-use the request 291 | self.disable_db = True 292 | self.uid = None 293 | 294 | def set_handler(self, endpoint, arguments, auth): 295 | # is this needed ? 296 | arguments ={k: v for k, v in arguments.items() 297 | if not k.startswith("_ignored_")} 298 | self.endpoint_arguments = arguments 299 | self.endpoint = endpoint 300 | self.auth_method = auth 301 | 302 | def _handle_exception(self, exception): 303 | """Called within an except block to allow converting exceptions 304 | to abitrary responses. Anything returned (except None) will 305 | be used as response.""" 306 | self._failed = exception # prevent tx commit 307 | if not isinstance(exception, NO_POSTMORTEM) \ 308 | and not isinstance(exception, werkzeug.exceptions.HTTPException): 309 | odoo.tools.debugger.post_mortem( 310 | odoo.tools.config, sys.exc_info()) 311 | # otherwise "no active exception to reraise" 312 | raise pycompat.reraise(type(exception), exception, sys.exc_info()[2]) 313 | 314 | def _call_function(self, *args, **kwargs): 315 | request = self 316 | if self.endpoint.routing['type'] != self._request_type: 317 | msg = "%s, %s: Function declared as capable of handling request of type '%s' but called with a request of type '%s'" 318 | params = (self.endpoint.original, self.httprequest.path, self.endpoint.routing['type'], self._request_type) 319 | _logger.info(msg, *params) 320 | raise werkzeug.exceptions.BadRequest(msg % params) 321 | 322 | if self.endpoint_arguments: 323 | kwargs.update(self.endpoint_arguments) 324 | 325 | # Backward for 7.0 326 | if self.endpoint.first_arg_is_req: 327 | args = (request,) + args 328 | 329 | # Correct exception handling and concurency retry 330 | @service_model.check 331 | def checked_call(___dbname, *a, **kw): 332 | # The decorator can call us more than once if there is an database error. In this 333 | # case, the request cursor is unusable. Rollback transaction to create a new one. 334 | if self._cr: 335 | self._cr.rollback() 336 | self.env.clear() 337 | result = self.endpoint(*a, **kw) 338 | if isinstance(result, Response) and result.is_qweb: 339 | # Early rendering of lazy responses to benefit from @service_model.check protection 340 | result.flatten() 341 | return result 342 | 343 | if self.db: 344 | return checked_call(self.db, *args, **kwargs) 345 | return self.endpoint(*args, **kwargs) 346 | 347 | @property 348 | def debug(self): 349 | """ Indicates whether the current request is in "debug" mode 350 | """ 351 | debug = 'debug' in self.httprequest.args 352 | if debug and self.httprequest.args.get('debug') == 'assets': 353 | debug = 'assets' 354 | 355 | # check if request from rpc in debug mode 356 | if not debug: 357 | debug = self.httprequest.environ.get('HTTP_X_DEBUG_MODE') 358 | 359 | if not debug and self.httprequest.referrer: 360 | debug = 'debug' in urls.url_parse(self.httprequest.referrer).decode_query() 361 | return debug 362 | 363 | @contextlib.contextmanager 364 | def registry_cr(self): 365 | warnings.warn('please use request.registry and request.cr directly', DeprecationWarning) 366 | yield (self.registry, self.cr) 367 | 368 | @property 369 | def registry(self): 370 | """ 371 | The registry to the database linked to this request. Can be ``None`` 372 | if the current request uses the ``none`` authentication. 373 | 374 | .. deprecated:: 8.0 375 | 376 | use :attr:`.env` 377 | """ 378 | return odoo.registry(self.db) 379 | 380 | @property 381 | def db(self): 382 | """ 383 | The database linked to this request. Can be ``None`` 384 | if the current request uses the ``none`` authentication. 385 | """ 386 | return self.session.db if not self.disable_db else None 387 | 388 | def csrf_token(self, time_limit=3600): 389 | """ Generates and returns a CSRF token for the current session 390 | 391 | :param time_limit: the CSRF token should only be valid for the 392 | specified duration (in second), by default 1h, 393 | ``None`` for the token to be valid as long as the 394 | current user's session is. 395 | :type time_limit: int | None 396 | :returns: ASCII token string 397 | """ 398 | token = self.session.sid 399 | max_ts = '' if not time_limit else int(time.time() + time_limit) 400 | msg = '%s%s' % (token, max_ts) 401 | secret = self.env['ir.config_parameter'].sudo().get_param('database.secret') 402 | assert secret, "CSRF protection requires a configured database secret" 403 | hm = hmac.new(secret.encode('ascii'), msg.encode('utf-8'), hashlib.sha1).hexdigest() 404 | return '%so%s' % (hm, max_ts) 405 | 406 | def validate_csrf(self, csrf): 407 | if not csrf: 408 | return False 409 | 410 | try: 411 | hm, _, max_ts = str(csrf).rpartition('o') 412 | except UnicodeEncodeError: 413 | return False 414 | 415 | if max_ts: 416 | try: 417 | if int(max_ts) < int(time.time()): 418 | return False 419 | except ValueError: 420 | return False 421 | 422 | token = self.session.sid 423 | 424 | msg = '%s%s' % (token, max_ts) 425 | secret = self.env['ir.config_parameter'].sudo().get_param('database.secret') 426 | assert secret, "CSRF protection requires a configured database secret" 427 | hm_expected = hmac.new(secret.encode('ascii'), msg.encode('utf-8'), hashlib.sha1).hexdigest() 428 | return consteq(hm, hm_expected) 429 | 430 | def route(route=None, **kw): 431 | """Decorator marking the decorated method as being a handler for 432 | requests. The method must be part of a subclass of ``Controller``. 433 | 434 | :param route: string or array. The route part that will determine which 435 | http requests will match the decorated method. Can be a 436 | single string or an array of strings. See werkzeug's routing 437 | documentation for the format of route expression ( 438 | http://werkzeug.pocoo.org/docs/routing/ ). 439 | :param type: The type of request, can be ``'http'`` or ``'json'``. 440 | :param auth: The type of authentication method, can on of the following: 441 | 442 | * ``user``: The user must be authenticated and the current request 443 | will perform using the rights of the user. 444 | * ``public``: The user may or may not be authenticated. If she isn't, 445 | the current request will perform using the shared Public user. 446 | * ``none``: The method is always active, even if there is no 447 | database. Mainly used by the framework and authentication 448 | modules. There request code will not have any facilities to access 449 | the database nor have any configuration indicating the current 450 | database nor the current user. 451 | :param methods: A sequence of http methods this route applies to. If not 452 | specified, all methods are allowed. 453 | :param cors: The Access-Control-Allow-Origin cors directive value. 454 | :param bool csrf: Whether CSRF protection should be enabled for the route. 455 | 456 | Defaults to ``True``. See :ref:`CSRF Protection 457 | ` for more. 458 | 459 | .. _csrf: 460 | 461 | .. admonition:: CSRF Protection 462 | :class: alert-warning 463 | 464 | .. versionadded:: 9.0 465 | 466 | Odoo implements token-based `CSRF protection 467 | `_. 468 | 469 | CSRF protection is enabled by default and applies to *UNSAFE* 470 | HTTP methods as defined by :rfc:`7231` (all methods other than 471 | ``GET``, ``HEAD``, ``TRACE`` and ``OPTIONS``). 472 | 473 | CSRF protection is implemented by checking requests using 474 | unsafe methods for a value called ``csrf_token`` as part of 475 | the request's form data. That value is removed from the form 476 | as part of the validation and does not have to be taken in 477 | account by your own form processing. 478 | 479 | When adding a new controller for an unsafe method (mostly POST 480 | for e.g. forms): 481 | 482 | * if the form is generated in Python, a csrf token is 483 | available via :meth:`request.csrf_token() 484 | `_, CSRF protection 501 | must be disabled on the endpoint. If possible, you may want 502 | to implement other methods of request validation (to ensure 503 | it is not called by an unrelated third-party). 504 | 505 | """ 506 | routing = kw.copy() 507 | assert 'type' not in routing or routing['type'] in ("http", "json") 508 | def decorator(f): 509 | if route: 510 | if isinstance(route, list): 511 | routes = route 512 | else: 513 | routes = [route] 514 | routing['routes'] = routes 515 | @functools.wraps(f) 516 | def response_wrap(*args, **kw): 517 | response = f(*args, **kw) 518 | if isinstance(response, Response) or f.routing_type == 'json': 519 | return response 520 | 521 | if isinstance(response, (bytes, pycompat.text_type)): 522 | return Response(response) 523 | 524 | if isinstance(response, werkzeug.exceptions.HTTPException): 525 | response = response.get_response(request.httprequest.environ) 526 | if isinstance(response, werkzeug.wrappers.BaseResponse): 527 | response = Response.force_type(response) 528 | response.set_default() 529 | return response 530 | 531 | _logger.warn(" returns an invalid response type for an http request" % (f.__module__, f.__name__)) 532 | return response 533 | response_wrap.routing = routing 534 | response_wrap.original_func = f 535 | return response_wrap 536 | return decorator 537 | 538 | class JsonRequest(WebRequest): 539 | """ Request handler for `JSON-RPC 2 540 | `_ over HTTP 541 | 542 | * ``method`` is ignored 543 | * ``params`` must be a JSON object (not an array) and is passed as keyword 544 | arguments to the handler method 545 | * the handler method's result is returned as JSON-RPC ``result`` and 546 | wrapped in the `JSON-RPC Response 547 | `_ 548 | 549 | Sucessful request:: 550 | 551 | --> {"jsonrpc": "2.0", 552 | "method": "call", 553 | "params": {"context": {}, 554 | "arg1": "val1" }, 555 | "id": null} 556 | 557 | <-- {"jsonrpc": "2.0", 558 | "result": { "res1": "val1" }, 559 | "id": null} 560 | 561 | Request producing a error:: 562 | 563 | --> {"jsonrpc": "2.0", 564 | "method": "call", 565 | "params": {"context": {}, 566 | "arg1": "val1" }, 567 | "id": null} 568 | 569 | <-- {"jsonrpc": "2.0", 570 | "error": {"code": 1, 571 | "message": "End user error message.", 572 | "data": {"code": "codestring", 573 | "debug": "traceback" } }, 574 | "id": null} 575 | 576 | """ 577 | _request_type = "json" 578 | 579 | def __init__(self, *args): 580 | super(JsonRequest, self).__init__(*args) 581 | 582 | self.jsonp_handler = None 583 | self.params = {} 584 | 585 | args = self.httprequest.args 586 | jsonp = args.get('jsonp') 587 | self.jsonp = jsonp 588 | request = None 589 | request_id = args.get('id') 590 | 591 | if jsonp and self.httprequest.method == 'POST': 592 | # jsonp 2 steps step1 POST: save call 593 | def handler(): 594 | self.session['jsonp_request_%s' % (request_id,)] = self.httprequest.form['r'] 595 | self.session.modified = True 596 | headers=[('Content-Type', 'text/plain; charset=utf-8')] 597 | r = werkzeug.wrappers.Response(request_id, headers=headers) 598 | return r 599 | self.jsonp_handler = handler 600 | return 601 | elif jsonp and args.get('r'): 602 | # jsonp method GET 603 | request = args.get('r') 604 | elif jsonp and request_id: 605 | # jsonp 2 steps step2 GET: run and return result 606 | request = self.session.pop('jsonp_request_%s' % (request_id,), '{}') 607 | else: 608 | # regular jsonrpc2 609 | request = self.httprequest.get_data().decode(self.httprequest.charset) 610 | 611 | # Read POST content or POST Form Data named "request" 612 | try: 613 | self.jsonrequest = json.loads(request) 614 | except ValueError: 615 | msg = 'Invalid JSON data: %r' % (request,) 616 | _logger.info('%s: %s', self.httprequest.path, msg) 617 | raise werkzeug.exceptions.BadRequest(msg) 618 | 619 | self.params = dict(self.jsonrequest.get("params", {})) 620 | self.context = self.params.pop('context', dict(self.session.context)) 621 | 622 | def _json_response(self, result=None, error=None): 623 | 624 | response = { 625 | 'jsonrpc': '2.0', 626 | 'id': self.jsonrequest.get('id') 627 | } 628 | if isinstance(result, dict) and result is not None and result.get('json'): 629 | mime = 'application/json' 630 | body = json.dumps(result.get('data')) 631 | return Response(body, status=200, headers=[('Content-Type', mime), ('Content-Length', len(body))]) 632 | if error is not None: 633 | response['error'] = error 634 | if result is not None: 635 | response['result'] = result 636 | 637 | if self.jsonp: 638 | # If we use jsonp, that's mean we are called from another host 639 | # Some browser (IE and Safari) do no allow third party cookies 640 | # We need then to manage http sessions manually. 641 | response['session_id'] = self.session.sid 642 | mime = 'application/javascript' 643 | body = "%s(%s);" % (self.jsonp, json.dumps(response, default=date_utils.json_default)) 644 | else: 645 | mime = 'application/json' 646 | body = json.dumps(response, default=date_utils.json_default) 647 | 648 | return Response( 649 | body, status=error and error.pop('http_status', 200) or 200, 650 | headers=[('Content-Type', mime), ('Content-Length', len(body))] 651 | ) 652 | 653 | def _handle_exception(self, exception): 654 | """Called within an except block to allow converting exceptions 655 | to arbitrary responses. Anything returned (except None) will 656 | be used as response.""" 657 | try: 658 | return super(JsonRequest, self)._handle_exception(exception) 659 | except Exception: 660 | if not isinstance(exception, (odoo.exceptions.Warning, SessionExpiredException, 661 | odoo.exceptions.except_orm, werkzeug.exceptions.NotFound)): 662 | _logger.exception("Exception during JSON request handling.") 663 | error = { 664 | 'code': 200, 665 | 'message': "Odoo Server Error", 666 | 'data': serialize_exception(exception) 667 | } 668 | if isinstance(exception, werkzeug.exceptions.NotFound): 669 | error['http_status'] = 404 670 | error['code'] = 404 671 | error['message'] = "404: Not Found" 672 | if isinstance(exception, AuthenticationError): 673 | error['code'] = 100 674 | error['message'] = "Odoo Session Invalid" 675 | if isinstance(exception, SessionExpiredException): 676 | error['code'] = 100 677 | error['message'] = "Odoo Session Expired" 678 | return self._json_response(error=error) 679 | 680 | def dispatch(self): 681 | if self.jsonp_handler: 682 | return self.jsonp_handler() 683 | try: 684 | rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG) 685 | rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG) 686 | if rpc_request_flag or rpc_response_flag: 687 | endpoint = self.endpoint.method.__name__ 688 | model = self.params.get('model') 689 | method = self.params.get('method') 690 | args = self.params.get('args', []) 691 | 692 | start_time = time.time() 693 | start_memory = 0 694 | if psutil: 695 | start_memory = memory_info(psutil.Process(os.getpid())) 696 | if rpc_request and rpc_response_flag: 697 | rpc_request.debug('%s: %s %s, %s', 698 | endpoint, model, method, pprint.pformat(args)) 699 | 700 | result = self._call_function(**self.params) 701 | 702 | if rpc_request_flag or rpc_response_flag: 703 | end_time = time.time() 704 | end_memory = 0 705 | if psutil: 706 | end_memory = memory_info(psutil.Process(os.getpid())) 707 | logline = '%s: %s %s: time:%.3fs mem: %sk -> %sk (diff: %sk)' % ( 708 | endpoint, model, method, end_time - start_time, start_memory / 1024, end_memory / 1024, (end_memory - start_memory)/1024) 709 | if rpc_response_flag: 710 | rpc_response.debug('%s, %s', logline, pprint.pformat(result)) 711 | else: 712 | rpc_request.debug(logline) 713 | 714 | return self._json_response(result) 715 | except Exception as e: 716 | return self._handle_exception(e) 717 | 718 | def serialize_exception(e): 719 | tmp = { 720 | "name": type(e).__module__ + "." + type(e).__name__ if type(e).__module__ else type(e).__name__, 721 | "debug": traceback.format_exc(), 722 | "message": ustr(e), 723 | "arguments": e.args, 724 | "exception_type": "internal_error" 725 | } 726 | if isinstance(e, odoo.exceptions.UserError): 727 | tmp["exception_type"] = "user_error" 728 | elif isinstance(e, odoo.exceptions.Warning): 729 | tmp["exception_type"] = "warning" 730 | elif isinstance(e, odoo.exceptions.RedirectWarning): 731 | tmp["exception_type"] = "warning" 732 | elif isinstance(e, odoo.exceptions.AccessError): 733 | tmp["exception_type"] = "access_error" 734 | elif isinstance(e, odoo.exceptions.MissingError): 735 | tmp["exception_type"] = "missing_error" 736 | elif isinstance(e, odoo.exceptions.AccessDenied): 737 | tmp["exception_type"] = "access_denied" 738 | elif isinstance(e, odoo.exceptions.ValidationError): 739 | tmp["exception_type"] = "validation_error" 740 | elif isinstance(e, odoo.exceptions.except_orm): 741 | tmp["exception_type"] = "except_orm" 742 | return tmp 743 | 744 | class HttpRequest(WebRequest): 745 | """ Handler for the ``http`` request type. 746 | 747 | matched routing parameters, query string parameters, form_ parameters 748 | and files are passed to the handler method as keyword arguments. 749 | 750 | In case of name conflict, routing parameters have priority. 751 | 752 | The handler method's result can be: 753 | 754 | * a falsy value, in which case the HTTP response will be an 755 | `HTTP 204`_ (No Content) 756 | * a werkzeug Response object, which is returned as-is 757 | * a ``str`` or ``unicode``, will be wrapped in a Response object and 758 | interpreted as HTML 759 | 760 | .. _form: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2 761 | .. _HTTP 204: http://tools.ietf.org/html/rfc7231#section-6.3.5 762 | """ 763 | _request_type = "http" 764 | 765 | def __init__(self, *args): 766 | super(HttpRequest, self).__init__(*args) 767 | params = collections.OrderedDict(self.httprequest.args) 768 | params.update(self.httprequest.form) 769 | params.update(self.httprequest.files) 770 | params.pop('session_id', None) 771 | self.params = params 772 | 773 | def _handle_exception(self, exception): 774 | """Called within an except block to allow converting exceptions 775 | to abitrary responses. Anything returned (except None) will 776 | be used as response.""" 777 | try: 778 | return super(HttpRequest, self)._handle_exception(exception) 779 | except SessionExpiredException: 780 | redirect = None 781 | req = request.httprequest 782 | if req.method == 'POST': 783 | request.session.save_request_data() 784 | redirect = '/web/proxy/post{r.full_path}'.format(r=req) 785 | elif not request.params.get('noredirect'): 786 | redirect = req.url 787 | if redirect: 788 | query = werkzeug.urls.url_encode({ 789 | 'redirect': redirect, 790 | }) 791 | return werkzeug.utils.redirect('/web/login?%s' % query) 792 | except werkzeug.exceptions.HTTPException as e: 793 | return e 794 | 795 | def dispatch(self): 796 | if request.httprequest.method == 'OPTIONS' and request.endpoint and request.endpoint.routing.get('cors'): 797 | headers = { 798 | 'Access-Control-Max-Age': 60 * 60 * 24, 799 | 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, X-Debug-Mode' 800 | } 801 | return Response(status=200, headers=headers) 802 | 803 | if request.httprequest.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE') \ 804 | and request.endpoint.routing.get('csrf', True): # csrf checked by default 805 | token = self.params.pop('csrf_token', None) 806 | if not self.validate_csrf(token): 807 | if token is not None: 808 | _logger.warn("CSRF validation failed on path '%s'", 809 | request.httprequest.path) 810 | else: 811 | _logger.warn("""No CSRF validation token provided for path '%s' 812 | 813 | Odoo URLs are CSRF-protected by default (when accessed with unsafe 814 | HTTP methods). See 815 | https://www.odoo.com/documentation/12.0/reference/http.html#csrf for 816 | more details. 817 | 818 | * if this endpoint is accessed through Odoo via py-QWeb form, embed a CSRF 819 | token in the form, Tokens are available via `request.csrf_token()` 820 | can be provided through a hidden input and must be POST-ed named 821 | `csrf_token` e.g. in your form add: 822 | 823 | 824 | 825 | * if the form is generated or posted in javascript, the token value is 826 | available as `csrf_token` on `web.core` and as the `csrf_token` 827 | value in the default js-qweb execution context 828 | 829 | * if the form is accessed by an external third party (e.g. REST API 830 | endpoint, payment gateway callback) you will need to disable CSRF 831 | protection (and implement your own protection if necessary) by 832 | passing the `csrf=False` parameter to the `route` decorator. 833 | """, request.httprequest.path) 834 | 835 | raise werkzeug.exceptions.BadRequest('Session expired (invalid CSRF token)') 836 | 837 | r = self._call_function(**self.params) 838 | if not r: 839 | r = Response(status=204) # no content 840 | return r 841 | 842 | def make_response(self, data, headers=None, cookies=None): 843 | """ Helper for non-HTML responses, or HTML responses with custom 844 | response headers or cookies. 845 | 846 | While handlers can just return the HTML markup of a page they want to 847 | send as a string if non-HTML data is returned they need to create a 848 | complete response object, or the returned data will not be correctly 849 | interpreted by the clients. 850 | 851 | :param basestring data: response body 852 | :param headers: HTTP headers to set on the response 853 | :type headers: ``[(name, value)]`` 854 | :param collections.Mapping cookies: cookies to set on the client 855 | """ 856 | response = Response(data, headers=headers) 857 | if cookies: 858 | for k, v in cookies.items(): 859 | response.set_cookie(k, v) 860 | return response 861 | 862 | def render(self, template, qcontext=None, lazy=True, **kw): 863 | """ Lazy render of a QWeb template. 864 | 865 | The actual rendering of the given template will occur at then end of 866 | the dispatching. Meanwhile, the template and/or qcontext can be 867 | altered or even replaced by a static response. 868 | 869 | :param basestring template: template to render 870 | :param dict qcontext: Rendering context to use 871 | :param bool lazy: whether the template rendering should be deferred 872 | until the last possible moment 873 | :param kw: forwarded to werkzeug's Response object 874 | """ 875 | response = Response(template=template, qcontext=qcontext, **kw) 876 | if not lazy: 877 | return response.render() 878 | return response 879 | 880 | def not_found(self, description=None): 881 | """ Shortcut for a `HTTP 404 882 | `_ (Not Found) 883 | response 884 | """ 885 | return werkzeug.exceptions.NotFound(description) 886 | 887 | #---------------------------------------------------------- 888 | # Controller and route registration 889 | #---------------------------------------------------------- 890 | addons_manifest = {} 891 | controllers_per_module = collections.defaultdict(list) 892 | 893 | class ControllerType(type): 894 | def __init__(cls, name, bases, attrs): 895 | super(ControllerType, cls).__init__(name, bases, attrs) 896 | 897 | # flag old-style methods with req as first argument 898 | for k, v in attrs.items(): 899 | if inspect.isfunction(v) and hasattr(v, 'original_func'): 900 | # Set routing type on original functions 901 | routing_type = v.routing.get('type') 902 | parent = [claz for claz in bases if isinstance(claz, ControllerType) and hasattr(claz, k)] 903 | parent_routing_type = getattr(parent[0], k).original_func.routing_type if parent else routing_type or 'http' 904 | if routing_type is not None and routing_type is not parent_routing_type: 905 | routing_type = parent_routing_type 906 | _logger.warn("Subclass re-defines with different type than original." 907 | " Will use original type: %r" % (cls.__module__, cls.__name__, k, parent_routing_type)) 908 | v.original_func.routing_type = routing_type or parent_routing_type 909 | 910 | spec = inspect.getargspec(v.original_func) 911 | first_arg = spec.args[1] if len(spec.args) >= 2 else None 912 | if first_arg in ["req", "request"]: 913 | v._first_arg_is_req = True 914 | 915 | # store the controller in the controllers list 916 | name_class = ("%s.%s" % (cls.__module__, cls.__name__), cls) 917 | class_path = name_class[0].split(".") 918 | if not class_path[:2] == ["odoo", "addons"]: 919 | module = "" 920 | else: 921 | # we want to know all modules that have controllers 922 | module = class_path[2] 923 | # but we only store controllers directly inheriting from Controller 924 | if not "Controller" in globals() or not Controller in bases: 925 | return 926 | controllers_per_module[module].append(name_class) 927 | 928 | Controller = ControllerType('Controller', (object,), {}) 929 | 930 | class EndPoint(object): 931 | def __init__(self, method, routing): 932 | self.method = method 933 | self.original = getattr(method, 'original_func', method) 934 | self.routing = routing 935 | self.arguments = {} 936 | 937 | @property 938 | def first_arg_is_req(self): 939 | # Backward for 7.0 940 | return getattr(self.method, '_first_arg_is_req', False) 941 | 942 | def __call__(self, *args, **kw): 943 | return self.method(*args, **kw) 944 | 945 | def routing_map(modules, nodb_only, converters=None): 946 | routing_map = werkzeug.routing.Map(strict_slashes=False, converters=converters) 947 | 948 | def get_subclasses(klass): 949 | def valid(c): 950 | return c.__module__.startswith('odoo.addons.') and c.__module__.split(".")[2] in modules 951 | subclasses = klass.__subclasses__() 952 | result = [] 953 | for subclass in subclasses: 954 | if valid(subclass): 955 | result.extend(get_subclasses(subclass)) 956 | if not result and valid(klass): 957 | result = [klass] 958 | return result 959 | 960 | for module in modules: 961 | if module not in controllers_per_module: 962 | continue 963 | 964 | for _, cls in controllers_per_module[module]: 965 | subclasses = list(unique(c for c in get_subclasses(cls) if c is not cls)) 966 | if subclasses: 967 | name = "%s (extended by %s)" % (cls.__name__, ', '.join(sub.__name__ for sub in subclasses)) 968 | cls = type(name, tuple(reversed(subclasses)), {}) 969 | 970 | o = cls() 971 | members = inspect.getmembers(o, inspect.ismethod) 972 | for _, mv in members: 973 | if hasattr(mv, 'routing'): 974 | routing = dict(type='http', auth='user', methods=None, routes=None) 975 | methods_done = list() 976 | # update routing attributes from subclasses(auth, methods...) 977 | for claz in reversed(mv.__self__.__class__.mro()): 978 | fn = getattr(claz, mv.__name__, None) 979 | if fn and hasattr(fn, 'routing') and fn not in methods_done: 980 | methods_done.append(fn) 981 | routing.update(fn.routing) 982 | if not nodb_only or routing['auth'] == "none": 983 | assert routing['routes'], "Method %r has not route defined" % mv 984 | endpoint = EndPoint(mv, routing) 985 | for url in routing['routes']: 986 | if routing.get("combine", False): 987 | # deprecated v7 declaration 988 | url = o._cp_path.rstrip('/') + '/' + url.lstrip('/') 989 | if url.endswith("/") and len(url) > 1: 990 | url = url[: -1] 991 | 992 | xtra_keys = 'defaults subdomain build_only strict_slashes redirect_to alias host'.split() 993 | kw = {k: routing[k] for k in xtra_keys if k in routing} 994 | routing_map.add(werkzeug.routing.Rule(url, endpoint=endpoint, methods=routing['methods'], **kw)) 995 | return routing_map 996 | 997 | #---------------------------------------------------------- 998 | # HTTP Sessions 999 | #---------------------------------------------------------- 1000 | class AuthenticationError(Exception): 1001 | pass 1002 | 1003 | class SessionExpiredException(Exception): 1004 | pass 1005 | 1006 | class OpenERPSession(werkzeug.contrib.sessions.Session): 1007 | def __init__(self, *args, **kwargs): 1008 | self.inited = False 1009 | self.modified = False 1010 | self.rotate = False 1011 | super(OpenERPSession, self).__init__(*args, **kwargs) 1012 | self.inited = True 1013 | self._default_values() 1014 | self.modified = False 1015 | 1016 | def __getattr__(self, attr): 1017 | return self.get(attr, None) 1018 | def __setattr__(self, k, v): 1019 | if getattr(self, "inited", False): 1020 | try: 1021 | object.__getattribute__(self, k) 1022 | except: 1023 | return self.__setitem__(k, v) 1024 | object.__setattr__(self, k, v) 1025 | 1026 | def authenticate(self, db, login=None, password=None, uid=None): 1027 | """ 1028 | Authenticate the current user with the given db, login and 1029 | password. If successful, store the authentication parameters in the 1030 | current session and request. 1031 | 1032 | :param uid: If not None, that user id will be used instead the login 1033 | to authenticate the user. 1034 | """ 1035 | 1036 | if uid is None: 1037 | wsgienv = request.httprequest.environ 1038 | env = dict( 1039 | base_location=request.httprequest.url_root.rstrip('/'), 1040 | HTTP_HOST=wsgienv['HTTP_HOST'], 1041 | REMOTE_ADDR=wsgienv['REMOTE_ADDR'], 1042 | ) 1043 | uid = odoo.registry(db)['res.users'].authenticate(db, login, password, env) 1044 | else: 1045 | security.check(db, uid, password) 1046 | self.rotate = True 1047 | self.db = db 1048 | self.uid = uid 1049 | self.login = login 1050 | self.session_token = uid and security.compute_session_token(self, request.env) 1051 | request.uid = uid 1052 | request.disable_db = False 1053 | 1054 | if uid: self.get_context() 1055 | return uid 1056 | 1057 | def check_security(self): 1058 | """ 1059 | Check the current authentication parameters to know if those are still 1060 | valid. This method should be called at each request. If the 1061 | authentication fails, a :exc:`SessionExpiredException` is raised. 1062 | """ 1063 | if not self.db or not self.uid: 1064 | raise SessionExpiredException("Session expired") 1065 | # We create our own environment instead of the request's one. 1066 | # to avoid creating it without the uid since request.uid isn't set yet 1067 | env = odoo.api.Environment(request.cr, self.uid, self.context) 1068 | # here we check if the session is still valid 1069 | if not security.check_session(self, env): 1070 | raise SessionExpiredException("Session expired") 1071 | 1072 | def logout(self, keep_db=False): 1073 | for k in list(self): 1074 | if not (keep_db and k == 'db'): 1075 | del self[k] 1076 | self._default_values() 1077 | self.rotate = True 1078 | 1079 | def _default_values(self): 1080 | self.setdefault("db", None) 1081 | self.setdefault("uid", None) 1082 | self.setdefault("login", None) 1083 | self.setdefault("session_token", None) 1084 | self.setdefault("context", {}) 1085 | 1086 | def get_context(self): 1087 | """ 1088 | Re-initializes the current user's session context (based on his 1089 | preferences) by calling res.users.get_context() with the old context. 1090 | 1091 | :returns: the new context 1092 | """ 1093 | assert self.uid, "The user needs to be logged-in to initialize his context" 1094 | self.context = request.env['res.users'].context_get() or {} 1095 | self.context['uid'] = self.uid 1096 | self._fix_lang(self.context) 1097 | return self.context 1098 | 1099 | def _fix_lang(self, context): 1100 | """ OpenERP provides languages which may not make sense and/or may not 1101 | be understood by the web client's libraries. 1102 | 1103 | Fix those here. 1104 | 1105 | :param dict context: context to fix 1106 | """ 1107 | lang = context.get('lang') 1108 | 1109 | # inane OpenERP locale 1110 | if lang == 'ar_AR': 1111 | lang = 'ar' 1112 | 1113 | # lang to lang_REGION (datejs only handles lang_REGION, no bare langs) 1114 | if lang in babel.core.LOCALE_ALIASES: 1115 | lang = babel.core.LOCALE_ALIASES[lang] 1116 | 1117 | context['lang'] = lang or 'en_US' 1118 | 1119 | def save_action(self, action): 1120 | """ 1121 | This method store an action object in the session and returns an integer 1122 | identifying that action. The method get_action() can be used to get 1123 | back the action. 1124 | 1125 | :param the_action: The action to save in the session. 1126 | :type the_action: anything 1127 | :return: A key identifying the saved action. 1128 | :rtype: integer 1129 | """ 1130 | saved_actions = self.setdefault('saved_actions', {"next": 1, "actions": {}}) 1131 | # we don't allow more than 10 stored actions 1132 | if len(saved_actions["actions"]) >= 10: 1133 | del saved_actions["actions"][min(saved_actions["actions"])] 1134 | key = saved_actions["next"] 1135 | saved_actions["actions"][key] = action 1136 | saved_actions["next"] = key + 1 1137 | self.modified = True 1138 | return key 1139 | 1140 | def get_action(self, key): 1141 | """ 1142 | Gets back a previously saved action. This method can return None if the action 1143 | was saved since too much time (this case should be handled in a smart way). 1144 | 1145 | :param key: The key given by save_action() 1146 | :type key: integer 1147 | :return: The saved action or None. 1148 | :rtype: anything 1149 | """ 1150 | saved_actions = self.get('saved_actions', {}) 1151 | return saved_actions.get("actions", {}).get(key) 1152 | 1153 | def save_request_data(self): 1154 | import uuid 1155 | req = request.httprequest 1156 | files = werkzeug.datastructures.MultiDict() 1157 | # NOTE we do not store files in the session itself to avoid loading them in memory. 1158 | # By storing them in the session store, we ensure every worker (even ones on other 1159 | # servers) can access them. It also allow stale files to be deleted by `session_gc`. 1160 | for f in req.files.values(): 1161 | storename = 'werkzeug_%s_%s.file' % (self.sid, uuid.uuid4().hex) 1162 | path = os.path.join(root.session_store.path, storename) 1163 | with open(path, 'w') as fp: 1164 | f.save(fp) 1165 | files.add(f.name, (storename, f.filename, f.content_type)) 1166 | self['serialized_request_data'] = { 1167 | 'form': req.form, 1168 | 'files': files, 1169 | } 1170 | 1171 | @contextlib.contextmanager 1172 | def load_request_data(self): 1173 | data = self.pop('serialized_request_data', None) 1174 | files = werkzeug.datastructures.MultiDict() 1175 | try: 1176 | if data: 1177 | # regenerate files filenames with the current session store 1178 | for name, (storename, filename, content_type) in data['files'].items(): 1179 | path = os.path.join(root.session_store.path, storename) 1180 | files.add(name, (path, filename, content_type)) 1181 | yield werkzeug.datastructures.CombinedMultiDict([data['form'], files]) 1182 | else: 1183 | yield None 1184 | finally: 1185 | # cleanup files 1186 | for f, _, _ in files.values(): 1187 | try: 1188 | os.unlink(f) 1189 | except IOError: 1190 | pass 1191 | 1192 | 1193 | def session_gc(session_store): 1194 | if random.random() < 0.001: 1195 | # we keep session one week 1196 | last_week = time.time() - 60*60*24*7 1197 | for fname in os.listdir(session_store.path): 1198 | path = os.path.join(session_store.path, fname) 1199 | try: 1200 | if os.path.getmtime(path) < last_week: 1201 | os.unlink(path) 1202 | except OSError: 1203 | pass 1204 | 1205 | #---------------------------------------------------------- 1206 | # WSGI Layer 1207 | #---------------------------------------------------------- 1208 | # Add potentially missing (older ubuntu) font mime types 1209 | mimetypes.add_type('application/font-woff', '.woff') 1210 | mimetypes.add_type('application/vnd.ms-fontobject', '.eot') 1211 | mimetypes.add_type('application/x-font-ttf', '.ttf') 1212 | # Add potentially missing (detected on windows) svg mime types 1213 | mimetypes.add_type('image/svg+xml', '.svg') 1214 | 1215 | class Response(werkzeug.wrappers.Response): 1216 | """ Response object passed through controller route chain. 1217 | 1218 | In addition to the :class:`werkzeug.wrappers.Response` parameters, this 1219 | class's constructor can take the following additional parameters 1220 | for QWeb Lazy Rendering. 1221 | 1222 | :param basestring template: template to render 1223 | :param dict qcontext: Rendering context to use 1224 | :param int uid: User id to use for the ir.ui.view render call, 1225 | ``None`` to use the request's user (the default) 1226 | 1227 | these attributes are available as parameters on the Response object and 1228 | can be altered at any time before rendering 1229 | 1230 | Also exposes all the attributes and methods of 1231 | :class:`werkzeug.wrappers.Response`. 1232 | """ 1233 | default_mimetype = 'text/html' 1234 | def __init__(self, *args, **kw): 1235 | template = kw.pop('template', None) 1236 | qcontext = kw.pop('qcontext', None) 1237 | uid = kw.pop('uid', None) 1238 | super(Response, self).__init__(*args, **kw) 1239 | self.set_default(template, qcontext, uid) 1240 | 1241 | def set_default(self, template=None, qcontext=None, uid=None): 1242 | self.template = template 1243 | self.qcontext = qcontext or dict() 1244 | self.qcontext['response_template'] = self.template 1245 | self.uid = uid 1246 | # Support for Cross-Origin Resource Sharing 1247 | if request.endpoint and 'cors' in request.endpoint.routing: 1248 | self.headers.set('Access-Control-Allow-Origin', request.endpoint.routing['cors']) 1249 | methods = 'GET, POST' 1250 | if request.endpoint.routing['type'] == 'json': 1251 | methods = 'POST' 1252 | elif request.endpoint.routing.get('methods'): 1253 | methods = ', '.join(request.endpoint.routing['methods']) 1254 | self.headers.set('Access-Control-Allow-Methods', methods) 1255 | 1256 | @property 1257 | def is_qweb(self): 1258 | return self.template is not None 1259 | 1260 | def render(self): 1261 | """ Renders the Response's template, returns the result 1262 | """ 1263 | env = request.env(user=self.uid or request.uid or odoo.SUPERUSER_ID) 1264 | self.qcontext['request'] = request 1265 | return env["ir.ui.view"].render_template(self.template, self.qcontext) 1266 | 1267 | def flatten(self): 1268 | """ Forces the rendering of the response's template, sets the result 1269 | as response body and unsets :attr:`.template` 1270 | """ 1271 | if self.template: 1272 | self.response.append(self.render()) 1273 | self.template = None 1274 | 1275 | class DisableCacheMiddleware(object): 1276 | def __init__(self, app): 1277 | self.app = app 1278 | def __call__(self, environ, start_response): 1279 | def start_wrapped(status, headers): 1280 | referer = environ.get('HTTP_REFERER', '') 1281 | parsed = urls.url_parse(referer) 1282 | debug = parsed.query.count('debug') >= 1 1283 | 1284 | new_headers = [] 1285 | unwanted_keys = ['Last-Modified'] 1286 | if debug: 1287 | new_headers = [('Cache-Control', 'no-cache')] 1288 | unwanted_keys += ['Expires', 'Etag', 'Cache-Control'] 1289 | 1290 | for k, v in headers: 1291 | if k not in unwanted_keys: 1292 | new_headers.append((k, v)) 1293 | 1294 | start_response(status, new_headers) 1295 | return self.app(environ, start_wrapped) 1296 | 1297 | class Root(object): 1298 | """Root WSGI application for the OpenERP Web Client. 1299 | """ 1300 | def __init__(self): 1301 | self._loaded = False 1302 | 1303 | @lazy_property 1304 | def session_store(self): 1305 | # Setup http sessions 1306 | path = odoo.tools.config.session_dir 1307 | _logger.debug('HTTP sessions stored in: %s', path) 1308 | return werkzeug.contrib.sessions.FilesystemSessionStore( 1309 | path, session_class=OpenERPSession, renew_missing=True) 1310 | 1311 | @lazy_property 1312 | def nodb_routing_map(self): 1313 | _logger.info("Generating nondb routing") 1314 | return routing_map([''] + odoo.conf.server_wide_modules, True) 1315 | 1316 | def __call__(self, environ, start_response): 1317 | """ Handle a WSGI request 1318 | """ 1319 | if not self._loaded: 1320 | self._loaded = True 1321 | self.load_addons() 1322 | return self.dispatch(environ, start_response) 1323 | 1324 | def load_addons(self): 1325 | """ Load all addons from addons path containing static files and 1326 | controllers and configure them. """ 1327 | # TODO should we move this to ir.http so that only configured modules are served ? 1328 | statics = {} 1329 | for addons_path in odoo.modules.module.ad_paths: 1330 | for module in sorted(os.listdir(str(addons_path))): 1331 | if module not in addons_manifest: 1332 | mod_path = opj(addons_path, module) 1333 | manifest_path = module_manifest(mod_path) 1334 | path_static = opj(addons_path, module, 'static') 1335 | if manifest_path and os.path.isdir(path_static): 1336 | manifest_data = open(manifest_path, 'rb').read() 1337 | manifest = ast.literal_eval(pycompat.to_native(manifest_data)) 1338 | if not manifest.get('installable', True): 1339 | continue 1340 | manifest['addons_path'] = addons_path 1341 | _logger.debug("Loading %s", module) 1342 | addons_manifest[module] = manifest 1343 | statics['/%s/static' % module] = path_static 1344 | 1345 | if statics: 1346 | _logger.info("HTTP Configuring static files") 1347 | app = werkzeug.wsgi.SharedDataMiddleware(self.dispatch, statics, cache_timeout=STATIC_CACHE) 1348 | self.dispatch = DisableCacheMiddleware(app) 1349 | 1350 | def setup_session(self, httprequest): 1351 | # recover or create session 1352 | session_gc(self.session_store) 1353 | 1354 | sid = httprequest.args.get('session_id') 1355 | explicit_session = True 1356 | if not sid: 1357 | sid = httprequest.headers.get("X-Openerp-Session-Id") 1358 | if not sid: 1359 | sid = httprequest.cookies.get('session_id') 1360 | explicit_session = False 1361 | if sid is None: 1362 | httprequest.session = self.session_store.new() 1363 | else: 1364 | httprequest.session = self.session_store.get(sid) 1365 | return explicit_session 1366 | 1367 | def setup_db(self, httprequest): 1368 | db = httprequest.session.db 1369 | # Check if session.db is legit 1370 | if db: 1371 | if db not in db_filter([db], httprequest=httprequest): 1372 | _logger.warn("Logged into database '%s', but dbfilter " 1373 | "rejects it; logging session out.", db) 1374 | httprequest.session.logout() 1375 | db = None 1376 | 1377 | if not db: 1378 | httprequest.session.db = db_monodb(httprequest) 1379 | 1380 | def setup_lang(self, httprequest): 1381 | if "lang" not in httprequest.session.context: 1382 | alang = httprequest.accept_languages.best or "en-US" 1383 | try: 1384 | code, territory, _, _ = babel.core.parse_locale(alang, sep='-') 1385 | if territory: 1386 | lang = '%s_%s' % (code, territory) 1387 | else: 1388 | lang = babel.core.LOCALE_ALIASES[code] 1389 | except (ValueError, KeyError): 1390 | lang = 'en_US' 1391 | httprequest.session.context["lang"] = lang 1392 | 1393 | def get_request(self, httprequest): 1394 | # deduce type of request 1395 | if httprequest.args.get('jsonp'): 1396 | return JsonRequest(httprequest) 1397 | if httprequest.mimetype in ("application/json", "application/json-rpc"): 1398 | return JsonRequest(httprequest) 1399 | else: 1400 | return HttpRequest(httprequest) 1401 | 1402 | def get_response(self, httprequest, result, explicit_session): 1403 | if isinstance(result, Response) and result.is_qweb: 1404 | try: 1405 | result.flatten() 1406 | except Exception as e: 1407 | if request.db: 1408 | result = request.registry['ir.http']._handle_exception(e) 1409 | else: 1410 | raise 1411 | 1412 | if isinstance(result, (bytes, pycompat.text_type)): 1413 | response = Response(result, mimetype='text/html') 1414 | else: 1415 | response = result 1416 | 1417 | save_session = (not request.endpoint) or request.endpoint.routing.get('save_session', True) 1418 | if not save_session: 1419 | return response 1420 | 1421 | if httprequest.session.should_save: 1422 | if httprequest.session.rotate: 1423 | self.session_store.delete(httprequest.session) 1424 | httprequest.session.sid = self.session_store.generate_key() 1425 | if httprequest.session.uid: 1426 | httprequest.session.session_token = security.compute_session_token(httprequest.session, request.env) 1427 | httprequest.session.modified = True 1428 | self.session_store.save(httprequest.session) 1429 | # We must not set the cookie if the session id was specified using a http header or a GET parameter. 1430 | # There are two reasons to this: 1431 | # - When using one of those two means we consider that we are overriding the cookie, which means creating a new 1432 | # session on top of an already existing session and we don't want to create a mess with the 'normal' session 1433 | # (the one using the cookie). That is a special feature of the Session Javascript class. 1434 | # - It could allow session fixation attacks. 1435 | if not explicit_session and hasattr(response, 'set_cookie'): 1436 | response.set_cookie( 1437 | 'session_id', httprequest.session.sid, max_age=90 * 24 * 60 * 60, httponly=True) 1438 | 1439 | return response 1440 | 1441 | def dispatch(self, environ, start_response): 1442 | """ 1443 | Performs the actual WSGI dispatching for the application. 1444 | """ 1445 | try: 1446 | httprequest = werkzeug.wrappers.Request(environ) 1447 | httprequest.app = self 1448 | httprequest.parameter_storage_class = werkzeug.datastructures.ImmutableOrderedMultiDict 1449 | threading.current_thread().url = httprequest.url 1450 | threading.current_thread().query_count = 0 1451 | threading.current_thread().query_time = 0 1452 | threading.current_thread().perf_t0 = time.time() 1453 | 1454 | explicit_session = self.setup_session(httprequest) 1455 | self.setup_db(httprequest) 1456 | self.setup_lang(httprequest) 1457 | 1458 | request = self.get_request(httprequest) 1459 | 1460 | def _dispatch_nodb(): 1461 | try: 1462 | func, arguments = self.nodb_routing_map.bind_to_environ(request.httprequest.environ).match() 1463 | except werkzeug.exceptions.HTTPException as e: 1464 | return request._handle_exception(e) 1465 | request.set_handler(func, arguments, "none") 1466 | result = request.dispatch() 1467 | return result 1468 | 1469 | with request: 1470 | db = request.session.db 1471 | if db: 1472 | try: 1473 | odoo.registry(db).check_signaling() 1474 | with odoo.tools.mute_logger('odoo.sql_db'): 1475 | ir_http = request.registry['ir.http'] 1476 | except (AttributeError, psycopg2.OperationalError, psycopg2.ProgrammingError): 1477 | # psycopg2 error or attribute error while constructing 1478 | # the registry. That means either 1479 | # - the database probably does not exists anymore 1480 | # - the database is corrupted 1481 | # - the database version doesnt match the server version 1482 | # Log the user out and fall back to nodb 1483 | request.session.logout() 1484 | # If requesting /web this will loop 1485 | if request.httprequest.path == '/web': 1486 | result = werkzeug.utils.redirect('/web/database/selector') 1487 | else: 1488 | result = _dispatch_nodb() 1489 | else: 1490 | result = ir_http._dispatch() 1491 | else: 1492 | result = _dispatch_nodb() 1493 | 1494 | response = self.get_response(httprequest, result, explicit_session) 1495 | return response(environ, start_response) 1496 | 1497 | except werkzeug.exceptions.HTTPException as e: 1498 | return e(environ, start_response) 1499 | 1500 | def get_db_router(self, db): 1501 | if not db: 1502 | return self.nodb_routing_map 1503 | return request.registry['ir.http'].routing_map() 1504 | 1505 | def db_list(force=False, httprequest=None): 1506 | dbs = odoo.service.db.list_dbs(force) 1507 | return db_filter(dbs, httprequest=httprequest) 1508 | 1509 | def db_filter(dbs, httprequest=None): 1510 | httprequest = httprequest or request.httprequest 1511 | h = httprequest.environ.get('HTTP_HOST', '').split(':')[0] 1512 | d, _, r = h.partition('.') 1513 | if d == "www" and r: 1514 | d = r.partition('.')[0] 1515 | if odoo.tools.config['dbfilter']: 1516 | d, h = re.escape(d), re.escape(h) 1517 | r = odoo.tools.config['dbfilter'].replace('%h', h).replace('%d', d) 1518 | dbs = [i for i in dbs if re.match(r, i)] 1519 | elif odoo.tools.config['db_name']: 1520 | # In case --db-filter is not provided and --database is passed, Odoo will 1521 | # use the value of --database as a comma seperated list of exposed databases. 1522 | exposed_dbs = set(db.strip() for db in odoo.tools.config['db_name'].split(',')) 1523 | dbs = sorted(exposed_dbs.intersection(dbs)) 1524 | return dbs 1525 | 1526 | def db_monodb(httprequest=None): 1527 | """ 1528 | Magic function to find the current database. 1529 | 1530 | Implementation details: 1531 | 1532 | * Magic 1533 | * More magic 1534 | 1535 | Returns ``None`` if the magic is not magic enough. 1536 | """ 1537 | httprequest = httprequest or request.httprequest 1538 | 1539 | dbs = db_list(True, httprequest) 1540 | 1541 | # try the db already in the session 1542 | db_session = httprequest.session.db 1543 | if db_session in dbs: 1544 | return db_session 1545 | 1546 | # if there is only one possible db, we take that one 1547 | if len(dbs) == 1: 1548 | return dbs[0] 1549 | return None 1550 | 1551 | def send_file(filepath_or_fp, mimetype=None, as_attachment=False, filename=None, mtime=None, 1552 | add_etags=True, cache_timeout=STATIC_CACHE, conditional=True): 1553 | """This is a modified version of Flask's send_file() 1554 | 1555 | Sends the contents of a file to the client. This will use the 1556 | most efficient method available and configured. By default it will 1557 | try to use the WSGI server's file_wrapper support. 1558 | 1559 | By default it will try to guess the mimetype for you, but you can 1560 | also explicitly provide one. For extra security you probably want 1561 | to send certain files as attachment (HTML for instance). The mimetype 1562 | guessing requires a `filename` or an `attachment_filename` to be 1563 | provided. 1564 | 1565 | Please never pass filenames to this function from user sources without 1566 | checking them first. 1567 | 1568 | :param filepath_or_fp: the filename of the file to send. 1569 | Alternatively a file object might be provided 1570 | in which case `X-Sendfile` might not work and 1571 | fall back to the traditional method. Make sure 1572 | that the file pointer is positioned at the start 1573 | of data to send before calling :func:`send_file`. 1574 | :param mimetype: the mimetype of the file if provided, otherwise 1575 | auto detection happens. 1576 | :param as_attachment: set to `True` if you want to send this file with 1577 | a ``Content-Disposition: attachment`` header. 1578 | :param filename: the filename for the attachment if it differs from the file's filename or 1579 | if using file object without 'name' attribute (eg: E-tags with StringIO). 1580 | :param mtime: last modification time to use for contitional response. 1581 | :param add_etags: set to `False` to disable attaching of etags. 1582 | :param conditional: set to `False` to disable conditional responses. 1583 | 1584 | :param cache_timeout: the timeout in seconds for the headers. 1585 | """ 1586 | if isinstance(filepath_or_fp, pycompat.string_types): 1587 | if not filename: 1588 | filename = os.path.basename(filepath_or_fp) 1589 | file = open(filepath_or_fp, 'rb') 1590 | if not mtime: 1591 | mtime = os.path.getmtime(filepath_or_fp) 1592 | else: 1593 | file = filepath_or_fp 1594 | if not filename: 1595 | filename = getattr(file, 'name', None) 1596 | 1597 | file.seek(0, 2) 1598 | size = file.tell() 1599 | file.seek(0) 1600 | 1601 | if mimetype is None and filename: 1602 | mimetype = mimetypes.guess_type(filename)[0] 1603 | if mimetype is None: 1604 | mimetype = 'application/octet-stream' 1605 | 1606 | headers = werkzeug.datastructures.Headers() 1607 | if as_attachment: 1608 | if filename is None: 1609 | raise TypeError('filename unavailable, required for sending as attachment') 1610 | headers.add('Content-Disposition', 'attachment', filename=filename) 1611 | headers['Content-Length'] = size 1612 | 1613 | data = wrap_file(request.httprequest.environ, file) 1614 | rv = Response(data, mimetype=mimetype, headers=headers, 1615 | direct_passthrough=True) 1616 | 1617 | if isinstance(mtime, str): 1618 | try: 1619 | server_format = odoo.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT 1620 | mtime = datetime.datetime.strptime(mtime.split('.')[0], server_format) 1621 | except Exception: 1622 | mtime = None 1623 | if mtime is not None: 1624 | rv.last_modified = mtime 1625 | 1626 | rv.cache_control.public = True 1627 | if cache_timeout: 1628 | rv.cache_control.max_age = cache_timeout 1629 | rv.expires = int(time.time() + cache_timeout) 1630 | 1631 | if add_etags and filename and mtime: 1632 | rv.set_etag('odoo-%s-%s-%s' % ( 1633 | mtime, 1634 | size, 1635 | adler32( 1636 | filename.encode('utf-8') if isinstance(filename, pycompat.text_type) 1637 | else filename 1638 | ) & 0xffffffff 1639 | )) 1640 | if conditional: 1641 | rv = rv.make_conditional(request.httprequest) 1642 | # make sure we don't send x-sendfile for servers that 1643 | # ignore the 304 status code for x-sendfile. 1644 | if rv.status_code == 304: 1645 | rv.headers.pop('x-sendfile', None) 1646 | return rv 1647 | 1648 | def content_disposition(filename): 1649 | filename = odoo.tools.ustr(filename) 1650 | escaped = urls.url_quote(filename, safe='') 1651 | 1652 | return "attachment; filename*=UTF-8''%s" % escaped 1653 | 1654 | #---------------------------------------------------------- 1655 | # RPC controller 1656 | #---------------------------------------------------------- 1657 | class CommonController(Controller): 1658 | 1659 | @route('/gen_session_id', type='json', auth="none") 1660 | def gen_session_id(self): 1661 | nsession = root.session_store.new() 1662 | return nsession.sid 1663 | 1664 | # main wsgi handler 1665 | root = Root() 1666 | -------------------------------------------------------------------------------- /docs/img/donation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lmarklil/odoo-dingtalk-connector/a3dd96a66a3c892e8efc340760fd196c1e4f8741/docs/img/donation.png -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from . import res_users, hr_department, res_config_settings 3 | -------------------------------------------------------------------------------- /models/hr_department.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from odoo import models, fields, api 3 | from odoo.addons.dingtalk_connector.dingtalk.main import DingTalk 4 | 5 | 6 | class HrDepartment(models.Model): 7 | _inherit = 'hr.department' 8 | 9 | dingtalk_id = fields.Char(string='钉钉部门ID') 10 | 11 | # 生成钉钉SDK实例 12 | def get_dingtalk(self): 13 | # 获取配置信息 14 | config = self.env['ir.config_parameter'].sudo() 15 | return DingTalk(config.get_param('dingtalk_app_key'), config.get_param('dingtalk_app_secret')) 16 | 17 | # 根据钉钉的部门信息创建部门 18 | def create_departments_from_dingtalk(self): 19 | # 删除系统创建的无用部门 20 | self.search([('name', '=', 'Administration')]).sudo().unlink() 21 | self.search([('name', '=', 'Sales')]).sudo().unlink() 22 | 23 | # 检查根部门是否存在 24 | root_department = self.search([('dingtalk_id', '=', 1)]).sudo() 25 | if not root_department: 26 | dingtalk = self.get_dingtalk() 27 | root_department_info = dingtalk.get_department_info(1) 28 | # 创建根部门 29 | root_department = self.env['hr.department'].sudo().create({ 30 | 'dingtalk_id': 1, 31 | 'name': root_department_info['name'] 32 | }) 33 | 34 | # 从根部门开始扫描并创建,根部门为1 35 | self.scan_and_create_departments(1, root_department['id']) 36 | self.department_clean_up() 37 | 38 | # 扫描并创建子部门 39 | def scan_and_create_departments(self, department_id, parent_department_id): 40 | # 调用钉钉API服务 41 | dingtalk = self.get_dingtalk() 42 | departments = dingtalk.get_departments(department_id).get('department') 43 | if departments != []: 44 | # 遍历部门列表 45 | for department in departments: 46 | # 检查部门是否存在,不存在时创建部门,否则检测部门信息是否更新,未更新则跳过创建继续扫描 47 | existing_department = self.search([('dingtalk_id', '=', department['id'])]) 48 | if not existing_department: 49 | parent_department = self.env['hr.department'].sudo().create({ 50 | 'dingtalk_id': department['id'], 51 | 'name': department['name'], 52 | 'parent_id': parent_department_id 53 | }) 54 | self.scan_and_create_departments(department['id'], parent_department['id']) 55 | else: 56 | # 检测数据是否更新 57 | if existing_department.name != department['name']: 58 | existing_department.write({ 59 | 'name': department['name'] 60 | }) 61 | self.scan_and_create_departments(department['id'], existing_department['id']) 62 | 63 | # 检查部门是否需要清理 64 | def department_clean_up(self): 65 | dingtalk = self.get_dingtalk() 66 | dingtalk_departments = dingtalk.get_departments(1, fetch_child=True).get('department') 67 | local_departments = self.search([]).sudo() 68 | for local_department in local_departments: 69 | unlink = True 70 | if int(local_department.dingtalk_id) != 1: 71 | for dingtalk_department in dingtalk_departments: 72 | if str(local_department.dingtalk_id) == str(dingtalk_department['id']): 73 | unlink = False 74 | break 75 | else: 76 | unlink = False 77 | if unlink: 78 | local_department.unlink() 79 | 80 | # 通过钉钉ID查找部门 81 | def search_department_by_dingtalk_id(self, id): 82 | department = self.search([('dingtalk_id', '=', id)]).sudo() 83 | # 检查部门是否存在,若不存在则同步部门 84 | if not department: 85 | self.create_departments_from_dingtalk() 86 | department = self.search([('dingtalk_id', '=', id)]).sudo() 87 | return department 88 | -------------------------------------------------------------------------------- /models/res_config_settings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import base64, string 3 | from random import choice 4 | from odoo.addons.dingtalk_connector.dingtalk.main import DingTalk 5 | from odoo import models, fields, api, _ 6 | from odoo.http import request 7 | from odoo.exceptions import UserError 8 | 9 | 10 | class ResConfigSettings(models.TransientModel): 11 | _inherit = 'res.config.settings' 12 | 13 | dingtalk_corp_id = fields.Char(string='钉钉corpId') 14 | dingtalk_app_key = fields.Char(string='钉钉AppKey') 15 | dingtalk_app_secret = fields.Char(string='钉钉AppSecret') 16 | dingtalk_sns_app_id = fields.Char(string='钉钉SNSAppId') 17 | dingtalk_sns_app_secret = fields.Char(string='钉钉SNSAppSecret') 18 | 19 | @api.multi 20 | def set_values(self): 21 | super(ResConfigSettings, self).set_values() 22 | params = self.env['ir.config_parameter'].sudo() 23 | params.set_param('dingtalk_corp_id', self[0].dingtalk_corp_id) 24 | params.set_param('dingtalk_app_key', self[0].dingtalk_app_key) 25 | params.set_param('dingtalk_sns_app_id', self[0].dingtalk_sns_app_id) 26 | params.set_param('dingtalk_sns_app_secret', self[0].dingtalk_sns_app_secret) 27 | 28 | @api.model 29 | def get_values(self): 30 | res = super(ResConfigSettings, self).get_values() 31 | params = self.env['ir.config_parameter'].sudo() 32 | res.update( 33 | dingtalk_corp_id=params.get_param('dingtalk_corp_id'), 34 | dingtalk_app_key=params.get_param('dingtalk_app_key'), 35 | dingtalk_app_secret=params.get_param('dingtalk_app_secret'), 36 | dingtalk_sns_app_id=params.get_param('dingtalk_sns_app_id'), 37 | dingtalk_sns_app_secret=params.get_param('dingtalk_sns_app_secret') 38 | ) 39 | return res 40 | 41 | def callback_api_register(self): 42 | """ 43 | 注册钉钉业务回调接口 44 | """ 45 | config = self.env['ir.config_parameter'].sudo() 46 | # 回调Tag 47 | call_back_tag = ['user_add_org'] 48 | # 生成Token 49 | token = self.generate_random_str(16) 50 | # 生成AESKey并进行Base64编码 51 | aes_key = base64.b64encode(self.generate_random_str(32).encode()).decode().rstrip('=') 52 | # 保存Token和AESKey 53 | config.set_param('dingtalk_call_back_api_token', token) 54 | config.set_param('dingtalk_call_back_api_aes_key', aes_key) 55 | # 回调Url 56 | call_back_url = request.httprequest.host_url + 'dingtalk/call_back' 57 | try: 58 | # 向钉钉接口发起回调接口注册请求 59 | dingtalk = DingTalk(config.get_param('dingtalk_app_key'), config.get_param('dingtalk_app_secret')) 60 | dingtalk.callback_api_register(call_back_tag, config.get_param('dingtalk_call_back_api_token'), 61 | config.get_param('dingtalk_call_back_api_aes_key'), call_back_url) 62 | except Exception as e: 63 | raise UserError( 64 | _('回调接口注册失败!\n\n错误原因:\n' + str( 65 | e) + '\n\n请检查:\n(1)基本参数是否正确。\n(2)回调地址是否已注册。\n(3)Odoo服务器是否可以被外网访问。\n(4)钉钉后台权限设置是否正确。')) 66 | 67 | def generate_random_str(self, size, 68 | chars=string.ascii_letters + string.ascii_lowercase + string.ascii_uppercase + string.digits): 69 | """ 70 | 生成随机字符串 71 | """ 72 | return ''.join(choice(chars) for i in range(size)) 73 | 74 | def update_users_and_departments(self): 75 | """ 76 | 手动同步成员与部门 77 | """ 78 | try: 79 | self.env['res.users'].sudo().create_users_from_dingtalk() 80 | except Exception as e: 81 | raise UserError(_('同步失败!\n\n错误原因:\n' + str(e))) 82 | -------------------------------------------------------------------------------- /models/res_users.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import random 3 | from odoo.addons.dingtalk_connector.dingtalk.main import DingTalk 4 | from odoo import models, fields, api 5 | from odoo.http import request 6 | from odoo.exceptions import AccessDenied 7 | 8 | 9 | class ResUsers(models.Model): 10 | _inherit = 'res.users' 11 | 12 | main_department_id = fields.Many2one(comodel_name="hr.department", string='主部门ID') 13 | department_ids = fields.Many2many(comodel_name="hr.department", string='部门IDS') 14 | dingtalk_id = fields.Char(string='钉钉用户ID') 15 | 16 | def _check_credentials(self, dingtalk_id): 17 | """ 18 | 用户验证 19 | """ 20 | try: 21 | return super(ResUsers, self)._check_credentials(dingtalk_id) 22 | except AccessDenied: 23 | # 判断是否为钉钉免登触发的用户验证方法 24 | if request.session.dingtalk_auth: 25 | request.session.dingtalk_auth = None 26 | else: 27 | raise AccessDenied 28 | 29 | def get_dingtalk(self): 30 | """ 31 | 获取钉钉API服务 32 | """ 33 | # 获取配置信息 34 | config = self.env['ir.config_parameter'].sudo() 35 | # 返回钉钉API服务 36 | return DingTalk(config.get_param('dingtalk_app_key'), config.get_param('dingtalk_app_secret')) 37 | 38 | def create_users_from_dingtalk(self): 39 | """ 40 | 获取所有钉钉用户并以此创建Odoo用户 41 | """ 42 | # 获取钉钉API服务 43 | dingtalk = self.get_dingtalk() 44 | # 获取并创建在职用户 45 | user_id_list = dingtalk.get_user_id_list() 46 | for user_id in user_id_list: 47 | self.create_user(user_id) 48 | self.user_clean_up(user_id_list) 49 | 50 | def create_user(self, user_id, active=True): 51 | """ 52 | 通过钉钉Id创建Odoo用户 53 | """ 54 | user = self.sudo().search([('dingtalk_id', '=', user_id), ('active', '=', active)]) 55 | if not user: 56 | password = 'dingtalk_id:' + user_id + '|key:' + str(random.randint(100000, 999999)) 57 | self.create_user_by_dingtalk_id(user_id, password, active=active) 58 | else: 59 | self.update_user_by_dingtalk_id(user) 60 | 61 | def create_user_by_dingtalk_id(self, dingtalk_id, password, active=True): 62 | """ 63 | 通过钉钉用户Id创建Odoo用户 64 | """ 65 | # 获取钉钉API服务 66 | dingtalk = self.get_dingtalk() 67 | user_detail = dingtalk.get_user_detail_by_ids(dingtalk_id).get('result')[0].get('field_list') 68 | 69 | # 将UserInfo转换成写入到Odoo的格式 70 | user_info = self.sudo().get_user_info_from_user_detail(user_detail) 71 | 72 | # 获取不重复的账号 73 | email = user_info.get('email') 74 | if email: 75 | email_str_array = email.split('@') 76 | email_name = email_str_array[0] 77 | email_host = email_str_array[1] 78 | if email_host != 'szpdc.com': 79 | # 返回True是因为免登的时候会判断是否注册失败,如果为True则注册失败,重定向到Odoo登陆页面 80 | return True 81 | email_count = len(self.search([('login', 'like', email_name)]).sudo()) 82 | if email_count > 0: 83 | email = email_name + str(email_count + 1) + '@' + email_host 84 | else: 85 | return True 86 | 87 | # 获取不重复的姓名 88 | name = user_info.get('name') 89 | name_count = len(self.search([('name', 'like', name)]).sudo()) 90 | if name_count > 0: 91 | name = name + str(name_count + 1) 92 | 93 | # 获取主部门ID 94 | main_department_id = self.env['hr.department'].search_department_by_dingtalk_id( 95 | user_info.get('main_department_id')).id 96 | 97 | # 获取部门IDS 98 | department_ids = [] 99 | for department_id in user_info.get('department_ids'): 100 | id = self.env['hr.department'].search_department_by_dingtalk_id(department_id).id 101 | if id: 102 | department_ids.append(id) 103 | 104 | # 创建Odoo用户 105 | values = { 106 | 'active': active, 107 | "login": email, 108 | "password": password, 109 | "name": name, 110 | 'email': email, 111 | 'department_ids': [(6, 0, department_ids)], 112 | 'main_department_id': main_department_id, 113 | 'groups_id': request.env.ref('base.group_user'), 114 | 'dingtalk_id': dingtalk_id 115 | } 116 | user = self.sudo().create(values) 117 | 118 | # 创建员工 119 | values = { 120 | 'user_id': user.id, 121 | 'name': name, 122 | 'department_id': main_department_id, 123 | 'mobile_phone': user_info.get('mobile') 124 | } 125 | employee = self.env['hr.employee'].sudo().create(values) 126 | 127 | def update_user_by_dingtalk_id(self, user): 128 | """ 129 | 更新用户信息 130 | """ 131 | # 获取钉钉API服务 132 | dingtalk = self.get_dingtalk() 133 | user_detail = dingtalk.get_user_detail_by_ids(user.dingtalk_id).get('result')[0].get('field_list') 134 | 135 | # 将UserInfo转换成写入到Odoo的格式 136 | user_info = self.sudo().get_user_info_from_user_detail(user_detail) 137 | # 获取主部门ID 138 | main_department_id = self.env['hr.department'].search_department_by_dingtalk_id( 139 | user_info.get('main_department_id')).id 140 | 141 | # 获取部门IDS 142 | department_ids = [] 143 | for department_id in user_info.get('department_ids'): 144 | id = self.env['hr.department'].search_department_by_dingtalk_id(department_id).id 145 | if id: 146 | department_ids.append(id) 147 | values = { 148 | 'department_ids': [(6, 0, department_ids)], 149 | 'main_department_id': main_department_id, 150 | } 151 | user.write(values) 152 | user_employee = user.employee_ids[0] 153 | values = { 154 | 'department_id': main_department_id 155 | } 156 | user_employee.write(values) 157 | 158 | def get_user_info_from_user_detail(self, user_detail): 159 | """ 160 | 从用户详情中生成用户基本信息 161 | """ 162 | user_info = {} 163 | for info in user_detail: 164 | fildcode = info.get('field_code') 165 | if fildcode == 'sys00-name': 166 | user_info['name'] = info.get('value') 167 | elif fildcode == 'sys00-email': 168 | user_info['email'] = info.get('value') 169 | elif fildcode == 'sys00-deptIds': 170 | department_ids = info.get('value').split('|') 171 | user_info['department_ids'] = department_ids 172 | elif fildcode == 'sys00-mainDeptId': 173 | user_info['main_department_id'] = info.get('value') 174 | elif fildcode == 'sys00-mobile': 175 | user_info['mobile'] = info.get('value') 176 | return user_info 177 | 178 | def user_clean_up(self, dingtalk_user_ids): 179 | """ 180 | 清理离职用户 181 | """ 182 | local_users = self.search([('dingtalk_id', '!=', None)]).sudo() 183 | for local_user in local_users: 184 | unlink = True 185 | for dingtalk_user in dingtalk_user_ids: 186 | if str(local_user.dingtalk_id) == str(dingtalk_user): 187 | unlink = False 188 | break; 189 | if unlink: 190 | local_user.write({ 191 | 'active': False 192 | }) 193 | -------------------------------------------------------------------------------- /static/description/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lmarklil/odoo-dingtalk-connector/a3dd96a66a3c892e8efc340760fd196c1e4f8741/static/description/icon.png -------------------------------------------------------------------------------- /views/dingtalk_connector_templates.xml: -------------------------------------------------------------------------------- 1 | 2 | 40 | 49 | 64 | -------------------------------------------------------------------------------- /views/res_config_settings_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | res.config.settings.view.form.inherit.dingtalk_connector 6 | res.config.settings 7 | 8 | 9 | 10 |
12 |

基本参数

13 |
14 |
15 | 基本参数是用于钉钉接口的身份认证,请务必填写,否则模块无法使用。其中corpId在钉钉开放平台获取,AppKey和AppSecret的获取方法请参考开发文档。获取SNSAppId和SNSAppSecret请参考 18 | 扫码登陆文档 19 | 20 |
21 |
22 |
23 |
30 |
31 |
32 |
33 |
40 |
41 |
42 |
43 |
50 |
51 |
52 |
53 |
60 |
61 |
62 |
63 |
70 |
71 |
72 |

业务回调接口

73 |
74 |
75 | 通过业务回调接口,钉钉的企业数据会自动同步到Odoo。详情请参考开发文档。 77 |
78 |
79 |
82 |
83 |

免登配置

84 |
85 |
86 |

钉钉连接器提供了免登功能,将Odoo添加到钉钉的「工作台」后可以实现免密码快速登陆,Odoo+钉钉的办公组合更加完美。以下是配置的步骤说明:

87 |

(1)在钉钉后台创建「自建应用」,创建过程请参考 89 | 开发文档。 90 |

91 |

(2)在应用的首页地址设置为:你的Odoo域名/dingtalk/sign/in。

92 |
93 |
94 |

手动同步

95 |
96 |
97 | 手动同步功能会从钉钉接口拉取所有的数据进行同步,若数据量大,同步需要的时间会比较长,请耐心等待。 98 |
99 |
100 |
103 |
104 |
105 |
106 |
107 |
108 |
--------------------------------------------------------------------------------