oauth2.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. /**
  2. * OAUTH2 授权
  3. * 登录,用户授权
  4. * <pre>
  5. * 作者:hugh zhuang
  6. * 邮箱:3378340995@qq.com
  7. * 日期:2018-10-08-下午3:29:34
  8. * 版权:广州流辰信息技术有限公司
  9. * </pre>
  10. */
  11. import { OAUTH2_URL } from '@/api/baseUrl'
  12. import request from '@/utils/request'
  13. import requestState from '@/constants/state'
  14. import { Message } from 'element-ui'
  15. import qs from 'qs'
  16. var AccessToken = function (data) {
  17. if (!(this instanceof AccessToken)) {
  18. return new AccessToken(data)
  19. }
  20. this.data = data
  21. }
  22. /**
  23. * 对返回结果的一层封装,如果遇见IBPS平台返回的错误,将返回一个错误
  24. * 参见:IBPS返回码说明
  25. */
  26. var wrapper = function (callback) {
  27. return function (err, data, res) {
  28. callback = callback || function () {}
  29. if (err) {
  30. err.name = 'IBPSAPI' + err.name
  31. return callback(err, data, res)
  32. }
  33. callback(null, data, res)
  34. }
  35. }
  36. /*!
  37. * 检查AccessToken是否有效,检查规则为当前时间和过期时间进行对比
  38. *
  39. * Examples:
  40. * ```
  41. * token.isValid();
  42. * ```
  43. */
  44. AccessToken.prototype.isValid = function () {
  45. return !!this.data.access_token && (new Date().getTime()) < (this.data.create_at + this.data.expires_in * 1000)
  46. }
  47. /*!
  48. * 处理token,更新过期时间
  49. */
  50. var processToken = function (that, callback) {
  51. var createAt = new Date().getTime()
  52. return function (err, data, res) {
  53. if (err) {
  54. return callback(err, data, res)
  55. }
  56. data.create_at = createAt
  57. // 20231106修改,将licence信息增加到接口返回数据
  58. if (res.variables && res.variables.licJson) {
  59. data.licJson = JSON.parse(res.variables.licJson)
  60. }
  61. // 存储token
  62. that.saveToken(data.uid, data, function (err) {
  63. callback(err, new AccessToken(data))
  64. })
  65. }
  66. }
  67. /**
  68. * 根据clientId和clientSecret创建OAuth接口的构造函数
  69. * 如需跨进程跨机器进行操作,access token需要进行全局维护
  70. * 使用token的优先级是:
  71. *
  72. * 1. 使用当前缓存的token对象
  73. * 2. 调用开发传入的获取token的异步方法,获得token之后使用(并缓存它)。
  74. * Examples:
  75. * ```
  76. * import IbpsOAuth from '@/utils/oauth2'
  77. * var oauthApi = new OAuth('clientId', 'clientSecret');
  78. * ```
  79. * @param {String} clientId 在平台上申请得到的clientId(或appid)
  80. * @param {String} clientSecret 在平台上申请得到的client secret(或app secret)
  81. * @param {Function} getToken 用于获取token的方法
  82. * @param {Function} saveToken 用于保存token的方法
  83. */
  84. var OAuth = function (clientId, clientSecret, getToken, saveToken) {
  85. this.clientId = clientId
  86. this.clientSecret = clientSecret
  87. this.statistic = ''
  88. // token的获取和存储
  89. this.store = {}
  90. this.getToken = getToken || function (uid, callback) {
  91. callback(null, this.store[uid])
  92. }
  93. if (!saveToken && process.env.NODE_ENV === 'production') {
  94. console.warn('Please dont save oauth token into memory under production')
  95. }
  96. this.saveToken = saveToken || function (uid, token, callback) {
  97. this.store[uid] = token
  98. callback(null)
  99. }
  100. this.defaults = {}
  101. }
  102. /*!
  103. * request的封装
  104. *
  105. * @param {String} url 路径
  106. * @param {Object} opts urllib选项
  107. * @param {Function} callback 回调函数
  108. */
  109. OAuth.prototype.request = function (opts, callback) {
  110. const options = {}
  111. Object.assign(options, this.defaults)
  112. if (typeof opts === 'function') {
  113. callback = opts
  114. opts = {}
  115. }
  116. for (const key in opts) {
  117. if (key !== 'headers') {
  118. options[key] = opts[key]
  119. } else {
  120. if (opts.headers) {
  121. options.headers = options.headers || {}
  122. Object.assign(options.headers, opts.headers)
  123. }
  124. }
  125. }
  126. request(options).then(response => {
  127. const { state } = response
  128. if (state === requestState.UNSUPORT || state === requestState.WARNING) {
  129. const err = new Error(response.message)
  130. err.state = state
  131. err.cause = response.cause
  132. callback(err)
  133. } else {
  134. callback(null, response.data, response)
  135. }
  136. }).catch(error => {
  137. callback(error)
  138. })
  139. }
  140. /**
  141. * 获取授权页面的URL地址
  142. * @param {String} redirect 授权后要跳转的地址
  143. * @param {String} state 开发者可提供的数据
  144. * @param {String} scope 作用范围,值为snsapi_userinfo和snsapi_base,前者用于弹出,后者用于跳转
  145. */
  146. OAuth.prototype.getAuthorizeURL = function (redirect, state, scope) {
  147. const url = OAUTH2_URL() + ''
  148. const info = {
  149. clientId: this.clientId,
  150. redirect_uri: redirect,
  151. response_type: 'code',
  152. scope: scope || 'snsapi_base',
  153. state: state || ''
  154. }
  155. return url + '?' + qs.stringify(info) + '#ibps_redirect'
  156. }
  157. /**
  158. * 获取授权页面的URL地址
  159. * @param {String} redirect 授权后要跳转的地址
  160. * @param {String} state 开发者可提供的数据
  161. * @param {String} scope 作用范围,值为snsapi_login,前者用于弹出,后者用于跳转
  162. */
  163. OAuth.prototype.getAuthorizeURLForWebsite = function (redirect, state, scope) {
  164. const url = OAUTH2_URL() + '/qrconnect'
  165. const info = {
  166. clientId: this.clientId,
  167. redirect_uri: redirect,
  168. response_type: 'code',
  169. scope: scope || 'snsapi_login',
  170. state: state || ''
  171. }
  172. return url + '?' + qs.stringify(info) + '#ibps_redirect'
  173. }
  174. /**
  175. * 根据授权获取到的code,换取access_token和uid
  176. * 获取uid之后,可以调用`IBPS.API`来获取更多用户信息
  177. * Examples:
  178. * ```
  179. * api.getAccessTokenByCode(code, callback);
  180. * ```
  181. * Callback:
  182. *
  183. * - `error`, 获取access token出现异常时的异常对象
  184. * - `result`, 成功时得到的响应结果
  185. *
  186. * Result:
  187. * ```
  188. * {
  189. * data: {
  190. * "access_token": "ACCESS_TOKEN",
  191. * "refresh_token": "REFRESH_TOKEN",
  192. * "uid": "uid",
  193. * "expires_in": 7200,
  194. * "scope": "SCOPE"
  195. * }
  196. * }
  197. * ```
  198. * @param {String} code 授权获取到的code
  199. * @param {Function} callback 回调函数
  200. */
  201. OAuth.prototype.getAccessTokenByCode = function (code, callback) {
  202. const args = {
  203. url: OAUTH2_URL() + '/authentication/apply',
  204. data: {
  205. client_id: this.clientId,
  206. client_secret: this.clientSecret,
  207. authorize_code: code,
  208. grant_type: 'authorization_code'
  209. },
  210. method: 'post'
  211. }
  212. this.request(args, wrapper(processToken(this, callback)))
  213. }
  214. /**
  215. * 密码授权模式
  216. * 根据用户名和密码,换取access token和uid
  217. * 获取uid之后,可以调用`IBPS.API`来获取更多用户信息
  218. * Examples:
  219. * ```
  220. * api.getAccessTokenByPassword(code, callback);
  221. * ```
  222. * Callback:
  223. *
  224. * - `error`, 获取access token出现异常时的异常对象
  225. * - `result`, 成功时得到的响应结果
  226. *
  227. * Result:
  228. * ```
  229. * {
  230. * data: {
  231. * "access_token": "ACCESS_TOKEN",
  232. * "refresh_token": "REFRESH_TOKEN",
  233. * "uid": "uid",
  234. * "expires_in": 7200,
  235. * "scope": "SCOPE"
  236. * }
  237. * }
  238. * ```
  239. * ```
  240. * @param {String} username 用户名
  241. * @param {String} password 密码
  242. * @param {Function} callback 回调函数
  243. */
  244. OAuth.prototype.getAccessTokenByPassword = function ({ username, password }, callback) {
  245. const args = {
  246. url: OAUTH2_URL() + '/authentication/apply',
  247. data: {
  248. client_id: this.clientId,
  249. client_secret: this.clientSecret,
  250. username: username,
  251. password: password,
  252. grant_type: 'password_credentials'
  253. },
  254. method: 'post'
  255. }
  256. this.request(args, wrapper(processToken(this, callback)))
  257. }
  258. /**
  259. * 根据refresh token,刷新access token,调用getAccessTokenByCode后才有效
  260. * Examples:
  261. * ```
  262. * api.refreshAccessToken(refreshToken, callback);
  263. * ```
  264. * Callback:
  265. *
  266. * - `err`, 刷新access token出现异常时的异常对象
  267. * - `result`, 成功时得到的响应结果
  268. *
  269. * Result:
  270. * ```
  271. * {
  272. * data: {
  273. * "access_token": "ACCESS_TOKEN",
  274. * "expires_in": 7200,
  275. * "refresh_token": "REFRESH_TOKEN",
  276. * "uid": "uid",
  277. * "remind_in": 7
  278. * }
  279. * }
  280. * ```
  281. * @param {String} refreshToken 刷新tonken
  282. * @param {Function} callback 回调函数
  283. */
  284. OAuth.prototype.refreshAccessToken = function (refreshToken, callback) {
  285. const args = {
  286. url: OAUTH2_URL() + '/authentication/apply',
  287. data: {
  288. client_id: this.clientId,
  289. client_secret: this.clientSecret,
  290. grant_type: 'refresh_token',
  291. refresh_token: refreshToken
  292. },
  293. method: 'post'
  294. }
  295. this.request(args, wrapper(processToken(this, callback)))
  296. }
  297. /**
  298. * 获取用户信息 【私有方法】
  299. * @param {*} options
  300. * @param {*} accessToken
  301. * @param {*} callback
  302. */
  303. OAuth.prototype._getUser = function (options, accessToken, callback) {
  304. const args = {
  305. url: OAUTH2_URL() + '/user/context',
  306. data: {
  307. access_token: accessToken,
  308. uid: options.uid,
  309. lang: options.lang || 'zh_CN'
  310. }
  311. }
  312. this.request(args, wrapper(callback))
  313. }
  314. /**
  315. * 根据uid,获取用户信息。
  316. * 当access token无效时,自动通过refresh token获取新的access token。然后再获取用户信息
  317. * Examples:
  318. * ```
  319. * api.getUser(uid, callback);
  320. * api.getUser(options, callback);
  321. * ```
  322. *
  323. * Options:
  324. * ```
  325. * // 或
  326. * {
  327. * "uid": "the user Id", // 必须
  328. * "lang": "the lang code" // zh_CN 简体,zh_TW 繁体,en 英语
  329. * }
  330. * ```
  331. * Callback:
  332. *
  333. * - `err`, 获取用户信息出现异常时的异常对象
  334. * - `result`, 成功时得到的响应结果
  335. *
  336. * Result:
  337. * ```
  338. * {
  339. * "uid": "uid",
  340. * "nickname": "NICKNAME",
  341. * "sex": "1",
  342. * "province": "PROVINCE"
  343. * "city": "CITY",
  344. * "country": "COUNTRY",
  345. * "headimgurl": "http://xxxxx.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
  346. * "privilege": [
  347. * "PRIVILEGE1"
  348. * "PRIVILEGE2"
  349. * ]
  350. * }
  351. * ```
  352. * @param {Object|String} options 传入uid或者参见Options
  353. * @param {Function} callback 回调函数
  354. */
  355. OAuth.prototype.getUser = function (options, callback) {
  356. if (typeof options !== 'object') {
  357. options = {
  358. uid: options
  359. }
  360. }
  361. const that = this
  362. this.getToken(options.uid, function (err, data) {
  363. if (err) {
  364. return callback(err)
  365. }
  366. // 没有token数据
  367. if (!data) {
  368. const message = 'No token for ' + options.uid + ', please authorize first.'
  369. Message({
  370. message: `${message}`,
  371. type: 'error',
  372. showClose: true,
  373. dangerouslyUseHTMLString: true,
  374. duration: 5 * 1000
  375. })
  376. const error = new Error(message)
  377. err.state = 'NoOAuthTokenError'
  378. return callback(error)
  379. }
  380. const token = new AccessToken(data)
  381. if (token.isValid()) {
  382. that._getUser(options, token.data.access_token, callback)
  383. } else {
  384. that.refreshAccessToken(token.data.refresh_token, function (err, token) {
  385. if (err) {
  386. return callback(err)
  387. }
  388. that._getUser(options, token.data.access_token, callback)
  389. })
  390. }
  391. })
  392. }
  393. /**
  394. * 检验授权凭证(access_token)是否有效。
  395. * Examples:
  396. * ```
  397. * api.verifyToken(uid, accessToken, callback);
  398. * ```
  399. * @param {String} uid 传入uid
  400. * @param {String} accessToken 待校验的access token
  401. * @param {Function} callback 回调函数
  402. */
  403. OAuth.prototype.verifyToken = function (uid, accessToken, callback) {
  404. const args = {
  405. url: OAUTH2_URL() + '/authentication/verify',
  406. params: {
  407. access_token: accessToken,
  408. uid: uid
  409. },
  410. method: 'post'
  411. }
  412. this.request(args, wrapper(callback))
  413. }
  414. /**
  415. * 用户名、密码方式登录。
  416. * Examples:
  417. * ```
  418. * api.userLogin(data, callback);
  419. * ```
  420. * @param {Objcct} data
  421. * username : 用户名
  422. * password : 密码
  423. * @param {Function} callback 回调函数
  424. */
  425. OAuth.prototype.userLogin = function (data, callback) {
  426. const args = {
  427. url: OAUTH2_URL() + '/user/login/apply',
  428. data: data,
  429. method: 'post'
  430. }
  431. this.request(args, wrapper(callback))
  432. }
  433. /**
  434. *
  435. *申请授权
  436. * Examples:
  437. * ```
  438. * api.authorize(login, callback);
  439. * ```
  440. * @param {Objcct} options
  441. * @param {Function} callback 回调函数
  442. */
  443. OAuth.prototype.authorize = function (data, callback) {
  444. const url = OAUTH2_URL() + '/authorize/apply'
  445. if (typeof data !== 'object') {
  446. data = {
  447. login_state: data
  448. }
  449. }
  450. data.client_id = this.clientId
  451. const args = {
  452. url,
  453. data: data,
  454. method: 'post'
  455. }
  456. this.request(args, wrapper(callback))
  457. }
  458. /**
  459. * 根据code,获取用户信息。
  460. * Examples:
  461. * ```
  462. * api.getUserByCode(code, callback);
  463. * ```
  464. * Callback:
  465. *
  466. * - `err`, 获取用户信息出现异常时的异常对象
  467. * - `result`, 成功时得到的响应结果
  468. *
  469. * Result:
  470. * ```
  471. * {
  472. * "uid": "uid",
  473. * "nickname": "NICKNAME",
  474. * "sex": "1",
  475. * "province": "PROVINCE"
  476. * "city": "CITY",
  477. * "country": "COUNTRY",
  478. * "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
  479. * "privilege": [
  480. * "PRIVILEGE1"
  481. * "PRIVILEGE2"
  482. * ]
  483. * }
  484. * ```
  485. * @param {Object|String} options 授权获取到的code
  486. * @param {Function} callback 回调函数
  487. */
  488. OAuth.prototype.getUserByCode = function (options, callback) {
  489. const that = this
  490. let lang
  491. let code
  492. if (typeof options === 'string') {
  493. code = options
  494. } else {
  495. lang = options.lang
  496. code = options.code
  497. }
  498. this.getAccessTokenByCode(code, function (err, result) {
  499. if (err) {
  500. return callback(err)
  501. }
  502. const uid = result.data.uid
  503. that.getUser({ uid: uid, lang: lang }, callback)
  504. })
  505. }
  506. /**
  507. * 通过登录获取access_token
  508. * @param {*} options
  509. * @param {*} callback
  510. */
  511. OAuth.prototype.getLoginCode = function (options, callback) {
  512. const that = this
  513. /**
  514. * 用户登录
  515. */
  516. this.userLogin(options, function (err, data, res) {
  517. if (err) {
  518. return callback(err)
  519. }
  520. that.statistic = res.variables.statistic // 判斷是否有统计权限
  521. // 没有token数据
  522. if (!data) {
  523. const message = '没有传回用户信息'
  524. Message({
  525. message: `${message}`,
  526. type: 'error',
  527. showClose: true,
  528. dangerouslyUseHTMLString: true,
  529. duration: 5 * 1000
  530. })
  531. const error = new Error(message)
  532. err.state = 'NoOAuthTokenError'
  533. return callback(error)
  534. }
  535. that.authorize(data, function (err1, data1) {
  536. if (err1) {
  537. return callback(err1)
  538. }
  539. that.getAccessTokenByCode(data1, callback)
  540. })
  541. })
  542. }
  543. export default OAuth