oauth2.js 14 KB

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