oauth2.js 14 KB

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