CliAuth.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. 'use strict'
  2. const AuthStrategy = require('@pm2/js-api/src/auth_strategies/strategy')
  3. const querystring = require('querystring');
  4. const http = require('http')
  5. const fs = require('fs')
  6. const url = require('url')
  7. const exec = require('child_process').exec
  8. const tryEach = require('async/tryEach')
  9. const path = require('path')
  10. const os = require('os')
  11. const needle = require('needle')
  12. const chalk = require('chalk')
  13. const cst = require('../../../../constants.js')
  14. const promptly = require('promptly')
  15. module.exports = class CliStrategy extends AuthStrategy {
  16. // the client will try to call this but we handle this part ourselves
  17. retrieveTokens (km, cb) {
  18. this.authenticated = false
  19. this.callback = cb
  20. this.km = km
  21. this.BASE_URI = 'https://id.keymetrics.io';
  22. }
  23. // so the cli know if we need to tell user to login/register
  24. isAuthenticated () {
  25. return new Promise((resolve, reject) => {
  26. if (this.authenticated) return resolve(true)
  27. let tokensPath = cst.PM2_IO_ACCESS_TOKEN
  28. fs.readFile(tokensPath, (err, tokens) => {
  29. if (err && err.code === 'ENOENT') return resolve(false)
  30. if (err) return reject(err)
  31. // verify that the token is valid
  32. try {
  33. tokens = JSON.parse(tokens || '{}')
  34. } catch (err) {
  35. fs.unlinkSync(tokensPath)
  36. return resolve(false)
  37. }
  38. // if the refresh tokens is here, the user could be automatically authenticated
  39. return resolve(typeof tokens.refresh_token === 'string')
  40. })
  41. })
  42. }
  43. verifyToken (refresh) {
  44. return this.km.auth.retrieveToken({
  45. client_id: this.client_id,
  46. refresh_token: refresh
  47. })
  48. }
  49. // called when we are sure the user asked to be logged in
  50. _retrieveTokens (optionalCallback) {
  51. const km = this.km
  52. const cb = this.callback
  53. tryEach([
  54. // try to find the token via the environment
  55. (next) => {
  56. if (!process.env.PM2_IO_TOKEN) {
  57. return next(new Error('No token in env'))
  58. }
  59. this.verifyToken(process.env.PM2_IO_TOKEN)
  60. .then((res) => {
  61. return next(null, res.data)
  62. }).catch(next)
  63. },
  64. // try to find it in the file system
  65. (next) => {
  66. fs.readFile(cst.PM2_IO_ACCESS_TOKEN, (err, tokens) => {
  67. if (err) return next(err)
  68. // verify that the token is valid
  69. tokens = JSON.parse(tokens || '{}')
  70. if (new Date(tokens.expire_at) > new Date(new Date().toISOString())) {
  71. return next(null, tokens)
  72. }
  73. this.verifyToken(tokens.refresh_token)
  74. .then((res) => {
  75. return next(null, res.data)
  76. }).catch(next)
  77. })
  78. },
  79. // otherwise make the whole flow
  80. (next) => {
  81. return this.authenticate((err, data) => {
  82. if (err instanceof Error) return next(err)
  83. // verify that the token is valid
  84. this.verifyToken(data.refresh_token)
  85. .then((res) => {
  86. return next(null, res.data)
  87. }).catch(next)
  88. })
  89. }
  90. ], (err, result) => {
  91. // if present run the optional callback
  92. if (typeof optionalCallback === 'function') {
  93. optionalCallback(err, result)
  94. }
  95. if (result.refresh_token) {
  96. this.authenticated = true
  97. let file = cst.PM2_IO_ACCESS_TOKEN
  98. fs.writeFile(file, JSON.stringify(result), () => {
  99. return cb(err, result)
  100. })
  101. } else {
  102. return cb(err, result)
  103. }
  104. })
  105. }
  106. authenticate (cb) {
  107. console.log(`${cst.PM2_IO_MSG} Using non-browser authentication.`)
  108. promptly.confirm(`${cst.PM2_IO_MSG} Do you have a pm2.io account? (y/n)`, (err, answer) => {
  109. // Either login or register
  110. return answer === true ? this.login(cb) : this.register(cb)
  111. })
  112. }
  113. login (cb) {
  114. let retry = () => {
  115. promptly.prompt(`${cst.PM2_IO_MSG} Your username or email: `, (err, username) => {
  116. if (err) return retry();
  117. promptly.password(`${cst.PM2_IO_MSG} Your password: `, { replace : '*' }, (err, password) => {
  118. if (err) return retry();
  119. console.log(`${cst.PM2_IO_MSG} Authenticating ...`)
  120. this._loginUser({
  121. username: username,
  122. password: password
  123. }, (err, data) => {
  124. if (err) {
  125. console.error(`${cst.PM2_IO_MSG_ERR} Failed to authenticate: ${err.message}`)
  126. return retry()
  127. }
  128. return cb(null, data)
  129. })
  130. })
  131. })
  132. }
  133. retry()
  134. }
  135. register (cb) {
  136. console.log(`${cst.PM2_IO_MSG} No problem ! We just need few informations to create your account`)
  137. var retry = () => {
  138. promptly.prompt(`${cst.PM2_IO_MSG} Please choose an username :`, {
  139. validator : this._validateUsername,
  140. retry : true
  141. }, (err, username) => {
  142. promptly.prompt(`${cst.PM2_IO_MSG} Please choose an email :`, {
  143. validator : this._validateEmail,
  144. retry : true
  145. },(err, email) => {
  146. promptly.password(`${cst.PM2_IO_MSG} Please choose a password :`, { replace : '*' }, (err, password) => {
  147. promptly.confirm(`${cst.PM2_IO_MSG} Do you accept the terms and privacy policy (https://pm2.io/legals/terms_conditions.pdf) ? (y/n)`, (err, answer) => {
  148. if (err) {
  149. console.error(chalk.bold.red(err));
  150. return retry()
  151. } else if (answer === false) {
  152. console.error(`${cst.PM2_IO_MSG_ERR} You must accept the terms and privacy policy to contiue.`)
  153. return retry()
  154. }
  155. this._registerUser({
  156. email : email,
  157. password : password,
  158. username : username
  159. }, (err, data) => {
  160. console.log('\n')
  161. if (err) {
  162. console.error(`${cst.PM2_IO_MSG_ERR} Unexpect error: ${err.message}`)
  163. console.error(`${cst.PM2_IO_MSG_ERR} You can also contact us to get help: contact@pm2.io`)
  164. return process.exit(1)
  165. }
  166. return cb(undefined, data)
  167. })
  168. })
  169. })
  170. })
  171. })
  172. }
  173. retry()
  174. }
  175. /**
  176. * Register function
  177. * @param opts.username
  178. * @param opts.password
  179. * @param opts.email
  180. */
  181. _registerUser (opts, cb) {
  182. const data = Object.assign(opts, {
  183. password_confirmation: opts.password,
  184. accept_terms: true
  185. })
  186. needle.post(this.BASE_URI + '/api/oauth/register', data, {
  187. json: true,
  188. headers: {
  189. 'X-Register-Provider': 'pm2-register',
  190. 'x-client-id': this.client_id
  191. }
  192. }, function (err, res, body) {
  193. if (err) return cb(err)
  194. if (body.email && body.email.message) return cb(new Error(body.email.message))
  195. if (body.username && body.username.message) return cb(new Error(body.username.message))
  196. if (!body.access_token) return cb(new Error(body.msg))
  197. return cb(null, {
  198. refresh_token : body.refresh_token.token,
  199. access_token : body.access_token.token
  200. })
  201. });
  202. }
  203. _loginUser (user_info, cb) {
  204. const URL_AUTH = '/api/oauth/authorize?response_type=token&scope=all&client_id=' +
  205. this.client_id + '&redirect_uri=http://localhost:43532';
  206. needle.get(this.BASE_URI + URL_AUTH, (err, res) => {
  207. if (err) return cb(err);
  208. var cookie = res.cookies;
  209. needle.post(this.BASE_URI + '/api/oauth/login', user_info, {
  210. cookies : cookie
  211. }, (err, resp, body) => {
  212. if (err) return cb(err)
  213. if (resp.statusCode != 200) return cb('Wrong credentials')
  214. var location = resp.headers['x-redirect']
  215. needle.get(this.BASE_URI + location, {
  216. cookies : cookie
  217. }, (err, res) => {
  218. if (err) return cb(err);
  219. var refresh_token = querystring.parse(url.parse(res.headers.location).query).access_token;
  220. needle.post(this.BASE_URI + '/api/oauth/token', {
  221. client_id : this.client_id,
  222. grant_type : 'refresh_token',
  223. refresh_token : refresh_token,
  224. scope : 'all'
  225. }, (err, res, body) => {
  226. if (err) return cb(err)
  227. return cb(null, body)
  228. })
  229. })
  230. })
  231. })
  232. }
  233. _validateEmail (email) {
  234. var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  235. if (re.test(email) == false)
  236. throw new Error('Not an email');
  237. return email;
  238. }
  239. _validateUsername (value) {
  240. if (value.length < 6) {
  241. throw new Error('Min length of 6');
  242. }
  243. return value;
  244. };
  245. deleteTokens (km) {
  246. return new Promise((resolve, reject) => {
  247. // revoke the refreshToken
  248. km.auth.revoke()
  249. .then(res => {
  250. // remove the token from the filesystem
  251. let file = cst.PM2_IO_ACCESS_TOKEN
  252. fs.unlinkSync(file)
  253. return resolve(res)
  254. }).catch(reject)
  255. })
  256. }
  257. }