├── .gitignore ├── LICENSE.txt ├── README.md ├── app └── jobs │ └── pull_wechat_avatar.rb ├── config ├── locales │ ├── client.en.yml │ ├── client.zh_CN.yml │ ├── server.en.yml │ └── server.zh_CN.yml └── settings.yml ├── lib └── wechat_authenticator.rb ├── plugin.rb └── spec ├── components └── auth │ └── wechat_authenticator_spec.rb ├── fixtures └── oauth_tokens.yml ├── helpers.rb └── plugin_spec.rb /.gitignore: -------------------------------------------------------------------------------- 1 | auto_generated 2 | gems 3 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Discourse 微信集成 2 | =================== 3 | 4 | Discourse wechat integration. 5 | 6 | 插件需要微信开放平台的 app id 和 secret。 7 | 8 | 插件生成了假的邮件地址,让用户用全屏直接用微信登录而无需输入其他信息。 9 | 登录地址为 `/auth/wechat`。 10 | 11 | 创建用户后,发送提示邮件让用户更改邮箱地址等。 12 | 13 | 插件提供了一个查询用户关联的 API:`/wechat/users/:unionid.json`,请使用 `api_key` 和 `api_username` GET 查询。并请用 HTTPS 保证安全。 14 | 15 | 其返回数据和 users 的返回数据一致,其中重要字段为 `custom_fields` 中的 `wechat_unionid` 和 `wechat_info` 字段: 16 | 17 | { 18 | "user_badges": [], 19 | "user": { 20 | "id": 459, 21 | "username": "random_username", 22 | "avatar_template": "/letter_avatar_proxy/v2/letter/r/c77e96/{size}.png", 23 | "name": null, 24 | "last_posted_at": null, 25 | "last_seen_at": "2016-04-09T10:36:37.239Z", 26 | "created_at": "2016-04-09T10:34:00.850Z", 27 | "website_name": null, 28 | "can_edit": true, 29 | "can_edit_username": true, 30 | "can_edit_email": true, 31 | "can_edit_name": true, 32 | "can_send_private_messages": true, 33 | "can_send_private_message_to_user": true, 34 | "trust_level": 0, 35 | "moderator": false, 36 | "admin": false, 37 | "title": null, 38 | "uploaded_avatar_id": null, 39 | "badge_count": 0, 40 | "has_title_badges": false, 41 | "custom_fields": { 42 | "wechat_unionid": "123456" 43 | }, 44 | "pending_count": 0, 45 | "profile_view_count": 0, 46 | "post_count": 0, 47 | "can_be_deleted": true, 48 | "can_delete_all_posts": true, 49 | "locale": null, 50 | "muted_category_ids": [], 51 | "tracked_category_ids": [], 52 | "watched_category_ids": [], 53 | "system_avatar_upload_id": null, 54 | "system_avatar_template": "/letter_avatar_proxy/v2/letter/r/c77e96/{size}.png", 55 | "gravatar_avatar_upload_id": null, 56 | "gravatar_avatar_template": null, 57 | "custom_avatar_upload_id": null, 58 | "custom_avatar_template": null, 59 | "muted_usernames": [], 60 | "mailing_list_posts_per_day": 2, 61 | "wechat_info": { 62 | "access_token": "123", 63 | "refresh_token": "456", 64 | "expires_at": "2016-04-09T12:32:40.131Z", 65 | "raw_info": { 66 | "we": 23, 67 | "city": { 68 | "nested": 23, 69 | "we": "23" 70 | } 71 | } 72 | }, 73 | "invited_by": null, 74 | "groups": [ 75 | { 76 | "id": 10, 77 | "automatic": true, 78 | "name": "trust_level_0", 79 | "user_count": 340, 80 | "alias_level": 0, 81 | "visible": true, 82 | "automatic_membership_email_domains": null, 83 | "automatic_membership_retroactive": false, 84 | "primary_group": false, 85 | "title": null, 86 | "grant_trust_level": null, 87 | "incoming_email": null, 88 | "notification_level": 2, 89 | "has_messages": false, 90 | "mentionable": false 91 | } 92 | ], 93 | "featured_user_badge_ids": [], 94 | "card_badge": null, 95 | "user_option": { 96 | "user_id": 459, 97 | "email_always": false, 98 | "mailing_list_mode": false, 99 | "email_digests": false, 100 | "email_private_messages": true, 101 | "email_direct": false, 102 | "external_links_in_new_tab": false, 103 | "dynamic_favicon": false, 104 | "enable_quoting": true, 105 | "disable_jump_reply": false, 106 | "digest_after_minutes": 20160, 107 | "automatically_unpin_topics": true, 108 | "auto_track_topics_after_msecs": 240000, 109 | "new_topic_duration_minutes": 2880, 110 | "email_previous_replies": 2, 111 | "email_in_reply_to": true, 112 | "like_notification_frequency": 1, 113 | "include_tl0_in_digests": false 114 | } 115 | } 116 | } 117 | 118 | 119 | 目前无法把已经建立的账号和微信绑定起来,后期可能考虑提供 API 直接加入 UnionId 的绑定,减少不必要的 OAuth 流程。 120 | 121 | ## 安装 122 | 123 | 在 `app.yml` 的 124 | 125 | hooks: 126 | after_code: 127 | - exec: 128 | cd: $home/plugins 129 | cmd: 130 | - mkdir -p plugins 131 | - git clone https://github.com/discourse/docker_manager.git 132 | 133 | 最后一行 `- git clone https://github.com/discourse/docker_manager.git` 后添加: 134 | 135 | - git clone https://github.com/fantasticfears/discourse-chinese-localization-pack.git 136 | 137 | ## 使用 138 | 139 | 140 | ## 许可协议 141 | 142 | GPLv2,由 [JPush][jpush] 支持开发。 143 | 144 | Copyright 2016. JPush, Erick Guan. 145 | 146 | [jpush]: community.jpush.cn 147 | -------------------------------------------------------------------------------- /app/jobs/pull_wechat_avatar.rb: -------------------------------------------------------------------------------- 1 | module Jobs 2 | 3 | class PullWechatAvatar < Jobs::Base 4 | sidekiq_options queue: 'default' 5 | 6 | def execute(args) 7 | user = User.find_by(id: args[:user_id]) 8 | avatar = UserAvatar.find_by(id: args[:avatar_id]) 9 | return if user.nil? || avatar.nil? 10 | 11 | avatar.update_wechat_avatar! 12 | if !user.uploaded_avatar_id && avatar.custom_upload_id 13 | user.update_column(:uploaded_avatar_id, avatar.custom_upload_id) 14 | end 15 | end 16 | end 17 | 18 | end 19 | -------------------------------------------------------------------------------- /config/locales/client.en.yml: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | 3 | en: 4 | js: 5 | login: 6 | wechat: 7 | title: "with Wechat" 8 | message: "Authenticating with Wechat by QR code (make sure pop up blockers are not enabled)" 9 | -------------------------------------------------------------------------------- /config/locales/client.zh_CN.yml: -------------------------------------------------------------------------------- 1 | zh_CN: 2 | js: 3 | login: 4 | wechat: 5 | title: "使用微信帐号登录" 6 | message: "使用微信帐号扫描二维码验证登录(请确保没有禁止浏览器弹出对话框)" 7 | -------------------------------------------------------------------------------- /config/locales/server.en.yml: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | 3 | en: 4 | site_settings: 5 | wechat_intergration_enabled: "Enable Wechat integration." 6 | -------------------------------------------------------------------------------- /config/locales/server.zh_CN.yml: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | 3 | zh_CN: 4 | site_settings: 5 | wechat_intergration_enabled: 启用微信集成。 6 | zh_l10n_wechat_client_id: "微信公众平台帐号验证的客户端帐号(Client id),到 https://open.weixin.qq.com/ 来注册获取" 7 | zh_l10n_wechat_client_secret: "微信公众平台帐号验证的客户端密码(Client secret),到 https://open.weixin.qq.com/ 来注册获取" 8 | dashboard: 9 | zh_l10n_wechat_config_warning: '服务器允许使用微信开放平台登录(zh_l10n_enable_wechat_logins),但是 client id 和 client secret 没有被设定。 到站点设置更新此设定。参考设定指南。' 10 | system_messages: 11 | wechat_login_notification: 12 | subject_template: "欢迎使用微信登录" 13 | text_body_template: | 14 | 你好,欢迎加入%{site_name}。 15 | 16 | 你使用了微信登录,因为论坛的技术限制,我们随机生成了你的用户名和邮箱。 17 | 18 | 为了方便你在网页上登录你的账号,我们建议你在[用户设置](%{user_preferences_url})中设置你的邮箱和用户名。 19 | 20 | 这一步骤很重要,否则你将不得不使用微信登录,甚至你可能会丢掉你的账号。在你确认了电子邮件后,你也可以根据需要开启邮件摘要和邮件回复提醒等功能。 21 | 22 | 想了解更多,请查看我们的[社群指引](%{base_url}/guidelines)。 23 | -------------------------------------------------------------------------------- /config/settings.yml: -------------------------------------------------------------------------------- 1 | plugins: 2 | wechat_intergration_enabled: 3 | default: true 4 | client: true 5 | wechat_intergration_client_id: 6 | default: '' 7 | wechat_intergration_client_secret: 8 | default: '' 9 | -------------------------------------------------------------------------------- /lib/wechat_authenticator.rb: -------------------------------------------------------------------------------- 1 | class WechatAuthenticator < ::Auth::Authenticator 2 | AUTHENTICATOR_NAME = 'wechat'.freeze 3 | 4 | def name 5 | AUTHENTICATOR_NAME 6 | end 7 | 8 | def after_authenticate(auth_token) 9 | result = Auth::Result.new 10 | 11 | data = auth_token[:info] 12 | credentials = auth_token[:credentials] 13 | raw_info = auth_token[:extra][:raw_info] 14 | name = data[:nickname] 15 | wechat_uid = raw_info[:unionid] 16 | plugin_hash = { 17 | access_token: credentials[:token], 18 | refresh_token: credentials[:refresh_token], 19 | expires_at: credentials[:expires_at].to_i.seconds.from_now, 20 | raw_info: raw_info 21 | } 22 | 23 | # no unionid, failed 24 | return result unless wechat_uid 25 | 26 | # update oauth hash anyway 27 | ::PluginStore.set(AUTHENTICATOR_NAME, "wechat_unionid_#{wechat_uid}", plugin_hash) 28 | 29 | # try to find existing wechat user entries 30 | current_info = UserCustomField.where(name: 'wechat_unionid', value: wechat_uid).first 31 | if current_info 32 | user = User.where(id: current_info.user_id).first 33 | else 34 | user = User.new(username: WechatNameSuggester.suggest_username(name), 35 | email: WechatNameSuggester.suggest_email(name)) 36 | user.custom_fields = { wechat_unionid: wechat_uid } 37 | user.save! 38 | user.email_tokens.delete_all 39 | 40 | unless user.email.include?('@') 41 | user.user_option.update( 42 | email_direct: false, 43 | email_digests: false, 44 | email_private_messages: false 45 | ) 46 | end 47 | 48 | user.activate 49 | user.pull_wechat_avatar 50 | Jobs.enqueue(:send_system_message, user_id: user.id, message_type: 'wechat_login_notification') 51 | end 52 | 53 | return result unless user.reload 54 | 55 | result.user = user 56 | result 57 | end 58 | 59 | def after_create_account(user, auth) 60 | end 61 | 62 | def register_middleware(omniauth) 63 | omniauth.provider :wechat, setup: lambda { |env| 64 | strategy = env['omniauth.strategy'] 65 | strategy.options[:client_id] = SiteSetting.wechat_intergration_client_id 66 | strategy.options[:client_secret] = SiteSetting.wechat_intergration_client_secret 67 | } 68 | end 69 | end 70 | 71 | module WechatNameSuggester 72 | def self.suggest_username(name, allow_username = nil) 73 | name = 'weixin' unless name.present? 74 | "#{find_available_username_based_on("wechat_#{name}", allow_username)}" 75 | end 76 | 77 | def self.suggest_email(name, allow_username = nil) 78 | self.suggest_username(name, allow_username) 79 | end 80 | 81 | def self.find_available_username_based_on(name, allow_username = nil) 82 | name = fix_username(name) 83 | i = 1 84 | attempt = name 85 | until attempt == allow_username || User.username_available?(attempt) 86 | suffix = i.to_s 87 | max_length = User.username_length.end - suffix.length - 1 88 | attempt = "#{name[0..max_length]}#{suffix}" 89 | i += 1 90 | end 91 | attempt 92 | end 93 | 94 | def self.fix_username(name) 95 | rightsize_username(sanitize_username(name)) 96 | end 97 | 98 | def self.sanitize_username(name) 99 | name = ActiveSupport::Inflector.transliterate(name) 100 | # 1. replace characters that aren't allowed with '_' 101 | name.gsub!(UsernameValidator::CONFUSING_EXTENSIONS, "_") 102 | name.gsub!(/[^\w.-]/, "_") 103 | # 2. removes unallowed leading characters 104 | name.gsub!(/^\W+/, "") 105 | # 3. removes unallowed trailing characters 106 | name = remove_unallowed_trailing_characters(name) 107 | # 4. unify special characters 108 | name.gsub!(/[-_.]{2,}/, "_") 109 | name 110 | end 111 | 112 | def self.remove_unallowed_trailing_characters(name) 113 | name.gsub!(/[^A-Za-z0-9]+$/, "") 114 | name 115 | end 116 | 117 | def self.rightsize_username(name) 118 | name = name[0, User.username_length.end] 119 | name = remove_unallowed_trailing_characters(name) 120 | name.ljust(User.username_length.begin, '1') 121 | end 122 | 123 | end 124 | 125 | # modified from gem 'omniauth-wechat-oauth2' 1.0; https://github.com/skinnyworm/omniauth-wechat-oauth2 126 | 127 | class OmniAuth::Strategies::Wechat < OmniAuth::Strategies::OAuth2 128 | option :name, "wechat" 129 | 130 | option :client_options, { 131 | site: "https://api.weixin.qq.com", 132 | authorize_url: "https://open.weixin.qq.com/connect/qrconnect#wechat_redirect", 133 | token_url: "/sns/oauth2/access_token", 134 | token_method: :get 135 | } 136 | 137 | option :authorize_params, {scope: "snsapi_login"} 138 | 139 | option :token_params, {parse: :json} 140 | 141 | uid do 142 | raw_info['openid'] 143 | end 144 | 145 | info do 146 | { 147 | nickname: raw_info['nickname'], 148 | sex: raw_info['sex'], 149 | province: raw_info['province'], 150 | city: raw_info['city'], 151 | country: raw_info['country'], 152 | headimgurl: raw_info['headimgurl'] 153 | } 154 | end 155 | 156 | extra do 157 | {raw_info: raw_info} 158 | end 159 | 160 | def request_phase 161 | params = client.auth_code.authorize_params.merge(redirect_uri: callback_url).merge(authorize_params) 162 | params["appid"] = params.delete("client_id") 163 | redirect client.authorize_url(params) 164 | end 165 | 166 | def raw_info 167 | @uid ||= access_token["openid"] 168 | @raw_info ||= begin 169 | access_token.options[:mode] = :query 170 | response = access_token.get("/sns/userinfo", :params => {"openid" => @uid}, parse: :text) 171 | @raw_info = JSON.parse(response.body.gsub(/[\u0000-\u001f]+/, '')) || {} 172 | @raw_info.merge!({"openid" => @uid }) 173 | @raw_info.merge!("unionid" => access_token["unionid"]) if access_token["unionid"] 174 | @raw_info 175 | end 176 | end 177 | 178 | protected 179 | def build_access_token 180 | params = { 181 | 'appid' => client.id, 182 | 'secret' => client.secret, 183 | 'code' => request.params['code'], 184 | 'grant_type' => 'authorization_code' 185 | }.merge(token_params.to_hash(symbolize_keys: true)) 186 | client.get_token(params, deep_symbolize(options.auth_token_params)) 187 | end 188 | end 189 | -------------------------------------------------------------------------------- /plugin.rb: -------------------------------------------------------------------------------- 1 | # name: Discourse 微信集成 2 | # about: Intergrates Wechat with Discourse 3 | # version: 0.1 4 | # author: Erick Guan 5 | 6 | enabled_site_setting :wechat_intergration_enabled 7 | 8 | PLUGIN_PREFIX = 'wechat_intergration_'.freeze 9 | PLUGIN_NAME = 'discourse_wechat_intergration'.freeze 10 | SITE_SETTING_NAME = 'wechat_intergration_enabled'.freeze 11 | USER_WECHAT_FILED_NAME = 'wechat_unionid'.freeze 12 | load File.expand_path('../lib/wechat_authenticator.rb', __FILE__) 13 | 14 | auth_provider authenticator: WechatAuthenticator.new, 15 | frame_width: 850, 16 | frame_height: 600, 17 | background_color: 'rgb(146, 230, 73)', 18 | glyph: '\f1d7', 19 | full_screen_login: true, 20 | enabled_setting: SITE_SETTING_NAME 21 | 22 | after_initialize do 23 | load File.expand_path("../app/jobs/pull_wechat_avatar.rb", __FILE__) 24 | 25 | module ::DiscourseWechatIntegration 26 | class Engine < ::Rails::Engine 27 | engine_name PLUGIN_NAME 28 | isolate_namespace DiscourseWechatIntegration 29 | end 30 | end 31 | 32 | DiscourseWechatIntegration::Engine.routes.draw do 33 | get "users/:unionid.json" => "wechat#show", defaults: {format: :json} 34 | end 35 | 36 | Discourse::Application.routes.append do 37 | mount ::DiscourseWechatIntegration::Engine, at: "/wechat" 38 | end 39 | 40 | class DiscourseWechatIntegration::WechatController < ::ApplicationController 41 | requires_plugin PLUGIN_NAME 42 | 43 | before_action :ensure_logged_in, only: [:show] 44 | 45 | def show 46 | @user = fetch_user_from_unionid(include_inactive: current_user.try(:staff?)) 47 | 48 | user_serializer = UserSerializer.new(@user, scope: guardian, root: 'user') 49 | 50 | # TODO remove this options from serializer 51 | user_serializer.omit_stats = true 52 | 53 | topic_id = params[:include_post_count_for].to_i 54 | if topic_id != 0 55 | user_serializer.topic_post_count = {topic_id => Post.where(topic_id: topic_id, user_id: @user.id).count } 56 | end 57 | 58 | render_json_dump(user_serializer) 59 | end 60 | 61 | private 62 | def fetch_user_from_unionid(opts = nil) 63 | opts ||= {} 64 | user = if params[:unionid] 65 | custom_field = UserCustomField.where(name: USER_WECHAT_FILED_NAME, value: params[:unionid]).first 66 | custom_field ? custom_field.user : nil 67 | end 68 | 69 | raise Discourse::NotFound unless user 70 | 71 | guardian.ensure_can_see!(user) 72 | user 73 | end 74 | end 75 | 76 | whitelist_staff_user_custom_field(USER_WECHAT_FILED_NAME) 77 | add_to_class(:user, :wechat_unionid) { custom_fields[USER_WECHAT_FILED_NAME] } 78 | add_to_serializer(:user, :include_wechat_info?, false) { scope.is_staff? && object.wechat_unionid } 79 | add_to_serializer(:user, :wechat_info, false) { object.wechat_unionid && PluginStore.get('wechat', "wechat_unionid_#{object.wechat_unionid}") } 80 | 81 | add_to_class(:user, :pull_wechat_avatar) do 82 | avatar = user_avatar || create_user_avatar 83 | 84 | Jobs.enqueue(:pull_wechat_avatar, user_id: self.id, avatar_id: avatar.id) 85 | 86 | # mark all the user's quoted posts as "needing a rebake" 87 | Post.rebake_all_quoted_posts(self.id) if self.uploaded_avatar_id_changed? 88 | end 89 | add_to_class(:user_avatar, :update_wechat_avatar!) do 90 | DistributedMutex.synchronize("pull_wechat_avatar_#{user_id}") do 91 | begin 92 | union_id = user.custom_fields['wechat_unionid'] 93 | return unless union_id 94 | plugin_row = PluginStore.get('wechat', "wechat_unionid_#{union_id}") 95 | return unless plugin_row 96 | image_url = plugin_row['raw_info']['headimgurl'] 97 | 98 | uri = URI.parse(image_url) 99 | return if uri && uri.scheme.nil? 100 | 101 | tempfile = FileHelper.download(image_url, SiteSetting.max_image_size_kb.kilobytes, "wechat_avatar") 102 | upload = Upload.create_for(user_id, tempfile, 'wechat_avatar.jpg', File.size(tempfile.path), origin: image_url, image_type: "avatar") 103 | 104 | if custom_upload_id != upload.id 105 | custom_upload_id.try(:destroy!) rescue nil 106 | self.custom_upload = upload 107 | save! 108 | end 109 | rescue OpenURI::HTTPError 110 | save! 111 | rescue SocketError 112 | # skip saving, we are not connected to the net 113 | Rails.logger.warn "Failed to download wechat avatar, socket error - user id #{user_id}" 114 | ensure 115 | tempfile.try(:close!) 116 | end 117 | end 118 | end 119 | 120 | AdminDashboardData.class_eval do 121 | def wechat_config_check 122 | if SiteSetting.public_send("#{PLUGIN_PREFIX}wechat_client_id").blank? || 123 | SiteSetting.public_send("#{PLUGIN_PREFIX}wechat_client_secret").blank? 124 | I18n.t("dashboard.#{PLUGIN_PREFIX}wechat_config_warning") 125 | end 126 | end 127 | end 128 | 129 | AdminDashboardData.add_problem_check :wechat_config_check 130 | end 131 | -------------------------------------------------------------------------------- /spec/components/auth/wechat_authenticator_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | load File.expand_path('../../../helpers.rb', __FILE__) 3 | 4 | RSpec.configure do |c| 5 | c.include PluginSpecHelpers 6 | end 7 | 8 | describe WechatAuthenticator do 9 | describe '.after_authenticate' do 10 | context 'with unionid returned' do 11 | let(:hash) { load_auth_hash('wechat') } 12 | after do 13 | User.where(email: 'no_email_wechat').delete_all 14 | UserCustomField.where(name: 'wechat_unionid').delete_all 15 | end 16 | 17 | it 'can authenticate existing user' do 18 | user = Fabricate(:user, email: 'no_email_wechat') 19 | UserCustomField.create(user_id: user.id, name: 'wechat_unionid', value: 'unionid') 20 | 21 | authenticator = described_class.new 22 | 23 | result = authenticator.after_authenticate(hash) 24 | 25 | expect(result.user.id).to eq(user.id) 26 | end 27 | 28 | it 'can create a user if non-existing' do 29 | authenticator = described_class.new 30 | 31 | result = authenticator.after_authenticate(hash) 32 | 33 | expect(result.user.id).to be_a(Fixnum) 34 | expect(result.user.custom_fields['wechat_unionid']).to eq('unionid') 35 | end 36 | 37 | it 'stores additional information' do 38 | authenticator = described_class.new 39 | 40 | authenticator.after_authenticate(hash) 41 | 42 | expect(PluginStore.get('wechat', 'wechat_unionid_unionid')[:raw_info]).to be_a(Hash) 43 | expect(PluginStore.get('wechat', 'wechat_unionid_unionid')[:raw_info][:city]).to eq('Shanghai') 44 | end 45 | 46 | it 'stores token credentials' do 47 | authenticator = described_class.new 48 | 49 | authenticator.after_authenticate(hash) 50 | 51 | row = PluginStore.get('wechat', 'wechat_unionid_unionid') 52 | 53 | expect(row[:access_token]).to eq('token') 54 | expect(row[:refresh_token]).to eq('another_token') 55 | expect(row[:expires_at]).to be_a(String) 56 | expect(row[:raw_info][:city]).to eq('Shanghai') 57 | end 58 | 59 | it 'creates and activates new user' do 60 | authenticator = described_class.new 61 | result = authenticator.after_authenticate(hash) 62 | 63 | expect(result.user).not_to eq(nil) 64 | expect(result.user.email_tokens.empty?).to eq(true) 65 | end 66 | 67 | it 'enqueue pull avatar job to new user & sends out a message for asking update emails to new user' do 68 | authenticator = described_class.new 69 | 70 | Jobs.expects(:enqueue).with(:pull_wechat_avatar, anything) 71 | Jobs.expects(:enqueue).with(:send_system_message, anything) 72 | 73 | authenticator.after_authenticate(hash) 74 | end 75 | 76 | it 'creates random username & random fake emails' do 77 | result_1 = described_class.new.after_authenticate(hash) 78 | result_2 = described_class.new.after_authenticate(load_auth_hash('wechat_2')) 79 | 80 | expect(result_1.user).not_to eq(nil) 81 | expect(result_2.user).not_to eq(nil) 82 | expect(result_1.user.id).not_to eq(result_2.user.id) 83 | end 84 | 85 | it 'generates a non-email for new user' do 86 | authenticator = described_class.new 87 | result = authenticator.after_authenticate(hash) 88 | 89 | expect(result.user.email.include?('@')).not_to eq(true) 90 | end 91 | 92 | it 'turn off email notifications for created user without legitimate email address' do 93 | authenticator = described_class.new 94 | result = authenticator.after_authenticate(hash) 95 | 96 | option = UserOption.where(user_id: result.user.id).first 97 | 98 | expect(option.email_direct).to eq(false) 99 | expect(option.email_digests).to eq(false) 100 | expect(option.email_private_messages).to eq(false) 101 | end 102 | end 103 | 104 | context 'without unionid returned' do 105 | let(:hash) { load_auth_hash('wechat_no_unionid') } 106 | 107 | it 'doesnt create or link any users' do 108 | authenticator = described_class.new 109 | result = authenticator.after_authenticate(hash) 110 | 111 | expect(result.user).to eq(nil) 112 | end 113 | end 114 | end 115 | 116 | describe '.after_create_account' do 117 | # no implementation 118 | # after { User.where(email: 'no_email_wechat').delete_all } 119 | 120 | # it 'dont touch email settings when user has email address' do 121 | # user = Fabricate(:user, email: 'email_wechat@test_wechat.test') 122 | # option = UserOption.where(user_id: user.id).first 123 | # 124 | # expect(option.email_direct).to eq(true) 125 | # expect(option.email_digests).to eq(true) 126 | # expect(option.email_private_messages).to eq(true) 127 | # end 128 | end 129 | end 130 | -------------------------------------------------------------------------------- /spec/fixtures/oauth_tokens.yml: -------------------------------------------------------------------------------- 1 | wechat: 2 | :provider: wechat 3 | :uid: '123456789' 4 | :info: 5 | :nickname: Nickname 6 | :sex: 1 7 | :province: Changning 8 | :city: Shanghai 9 | :country: China 10 | :headimgurl: http://image_url 11 | :credentials: 12 | :token: token 13 | :refresh_token: another_token 14 | :expires_at: 7200 15 | :expires: true 16 | :extra: 17 | :raw_info: 18 | :openid: openid 19 | :unionid: unionid 20 | :nickname: Nickname 21 | :sex: 1 22 | :province: Changning 23 | :city: Shanghai 24 | :country: China 25 | :headimgurl: http://image_url 26 | wechat_2: 27 | :provider: wechat 28 | :uid: '223456789' 29 | :info: 30 | :nickname: Nickname 31 | :sex: 1 32 | :province: Changning 33 | :city: Shanghai 34 | :country: China 35 | :headimgurl: http://image_url 36 | :credentials: 37 | :token: token 38 | :refresh_token: another_token 39 | :expires_at: 7200 40 | :expires: true 41 | :extra: 42 | :raw_info: 43 | :openid: openid 44 | :unionid: unionid_2 45 | :nickname: Nickname 46 | :sex: 1 47 | :province: Changning 48 | :city: Shanghai 49 | :country: China 50 | :headimgurl: http://image_url 51 | wechat_no_unionid: 52 | :provider: wechat 53 | :uid: '123456789' 54 | :info: 55 | :nickname: Nickname 56 | :sex: 1 57 | :province: Changning 58 | :city: Shanghai 59 | :country: China 60 | :headimgurl: http://image_url 61 | :credentials: 62 | :token: token 63 | :refresh_token: another_token 64 | :expires_at: 7200 65 | :expires: true 66 | :extra: 67 | :raw_info: 68 | :openid: openid 69 | :nickname: Nickname 70 | :sex: 1 71 | :province: Changning 72 | :city: Shanghai 73 | :country: China 74 | :headimgurl: http://image_url 75 | -------------------------------------------------------------------------------- /spec/helpers.rb: -------------------------------------------------------------------------------- 1 | module PluginSpecHelpers 2 | def load_auth_hash(name) 3 | YAML.load_file(File.expand_path('../fixtures/oauth_tokens.yml', __FILE__))[name] 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/plugin_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | load File.expand_path('../helpers.rb', __FILE__) 4 | 5 | describe 'discourse-wechat-integration' do 6 | it 'load the authenticator' do 7 | expect(Discourse.auth_providers.any? { |a| a.authenticator.class.name.demodulize == "WechatAuthenticator" }).to be_truthy 8 | end 9 | end 10 | --------------------------------------------------------------------------------