oauth2.js 14 KB

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