oauth2.js 15 KB

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