| 1 | ( function () { |
| 2 | |
| 3 | /** |
| 4 | * @typedef {Object} mw.Api.UserInfo |
| 5 | * @property {string[]} groups User groups that the current user belongs to |
| 6 | * @property {string[]} rights Current user's rights |
| 7 | */ |
| 8 | |
| 9 | Object.assign( mw.Api.prototype, /** @lends mw.Api.prototype */ { |
| 10 | |
| 11 | /** |
| 12 | * Get the current user's groups and rights. |
| 13 | * |
| 14 | * @since 1.27 |
| 15 | * @return {jQuery.Promise<mw.Api.UserInfo>} |
| 16 | */ |
| 17 | getUserInfo: function () { |
| 18 | return this.get( { |
| 19 | action: 'query', |
| 20 | meta: 'userinfo', |
| 21 | uiprop: [ 'groups', 'rights' ] |
| 22 | } ).then( ( data ) => { |
| 23 | if ( data.query && data.query.userinfo ) { |
| 24 | return data.query.userinfo; |
| 25 | } |
| 26 | return $.Deferred().reject().promise(); |
| 27 | } ); |
| 28 | }, |
| 29 | |
| 30 | /** |
| 31 | * Extend an API parameter object with an assertion that the user won't change. |
| 32 | * |
| 33 | * This is useful for API calls which create new revisions or log entries. When the current |
| 34 | * page was loaded when the user was logged in, but at the time of the API call the user |
| 35 | * is not logged in anymore (e.g. due to session expiry), their IP is recorded in the page |
| 36 | * history or log, which can cause serious privacy issues. Extending the API parameters via |
| 37 | * this method ensures that that won't happen, by checking the user's identity that was |
| 38 | * embedded into the page when it was rendered against the active session on the server. |
| 39 | * |
| 40 | * When the assertion fails, the API request will fail, with one of the following error codes: |
| 41 | * - apierror-assertanonfailed: when the client-side logic thinks the user is anonymous |
| 42 | * but the server thinks it is logged in; |
| 43 | * - apierror-assertuserfailed: when the client-side logic thinks the user is logged in but the |
| 44 | * server thinks it is anonymous; |
| 45 | * - apierror-assertnameduserfailed: when both the client-side logic and the server thinks the |
| 46 | * user is logged in but they see it logged in under a different username. |
| 47 | * |
| 48 | * @example |
| 49 | * api.postWithToken( 'csrf', api.assertCurrentUser( { action: 'edit', ... } ) ) |
| 50 | * |
| 51 | * @since 1.27 |
| 52 | * @param {Object} query Query parameters. The object will not be changed. |
| 53 | * @return {Object} |
| 54 | */ |
| 55 | assertCurrentUser: function ( query ) { |
| 56 | const user = mw.config.get( 'wgUserName' ), |
| 57 | assertParams = {}; |
| 58 | |
| 59 | if ( user !== null ) { |
| 60 | assertParams.assert = 'user'; |
| 61 | assertParams.assertuser = user; |
| 62 | } else { |
| 63 | assertParams.assert = 'anon'; |
| 64 | } |
| 65 | |
| 66 | return Object.assign( assertParams, query ); |
| 67 | } |
| 68 | |
| 69 | } ); |
| 70 | |
| 71 | }() ); |