Browse Source

Merge pull request #4 from ScreepsMods/steam

Added steam OpenID 2 auth support
ags131 2 years ago
parent
commit
392f720849
6 changed files with 1823 additions and 4 deletions
  1. 4
    1
      lib/backend.js
  2. 6
    0
      lib/index.js
  3. 91
    0
      lib/steam/index.js
  4. BIN
      out.gif
  5. 5
    3
      package.json
  6. 1717
    0
      yarn.lock

+ 4
- 1
lib/backend.js View File

@@ -18,10 +18,12 @@ module.exports = function (cconfig, authIns) {
18 18
   config.auth.info = {
19 19
     name: "screepsmod-auth", 
20 20
     version: require('../package.json').version, 
21
-    allowRegistration: !process.env.SERVER_PASSWORD
21
+    allowRegistration: !process.env.SERVER_PASSWORD,
22
+    steam: true
22 23
   }
23 24
   config.auth.router = new express.Router()
24 25
   config.backend.on('expressPreConfig',function (app) {
26
+    process.on('SIGTERM', ()=>process.exit())
25 27
     app.use(config.auth.router)
26 28
   })
27 29
   setupRouter(config)
@@ -77,6 +79,7 @@ function setupRouter (config) {
77 79
   router.get('/authmod', (req, res) => res.redirect('api/authmod'))
78 80
   router.get('/api/authmod', (req, res) => res.json(Object.assign({ ok: 1 },config.auth.info)))
79 81
   require('./register')(config)
82
+  require('./steam')(config)
80 83
 }
81 84
 
82 85
 function bodyParse (req, res, next) {

+ 6
- 0
lib/index.js View File

@@ -1,8 +1,14 @@
1 1
 const Auth = require('./auth')
2
+const ini = require('ini')
2 3
 
3 4
 module.exports = function(config){
5
+  let screepsrc = {}
6
+  try {
7
+    screepsrc = ini.parse(fs.readFileSync('./.screepsrc', {encoding: 'utf8'}))
8
+  } catch (e) { }
4 9
   let auth = new Auth()
5 10
   config.auth = {
11
+    screepsrc,
6 12
     checkPassword(salt,pass,proposed){
7 13
       return auth.verify_password(salt,pass,proposed)
8 14
     },

+ 91
- 0
lib/steam/index.js View File

@@ -0,0 +1,91 @@
1
+const path = require('path')
2
+const express = require('express')
3
+const bodyParser = require('body-parser')
4
+const cookieParser = require('cookie-parser')
5
+
6
+const passport = require('passport')
7
+const SteamStrategy = require('passport-steam').Strategy
8
+
9
+const authlib = require(path.join(path.dirname(require.main.filename), '../lib/authlib'))
10
+
11
+const app = new express.Router()
12
+
13
+module.exports = function (config) {
14
+  // Issuer.discover('https://steamcommunity.com/openid/')
15
+    // .then((steamIssuer) => {
16
+  let registered = false
17
+
18
+  app.use(cookieParser())
19
+
20
+  app.get('/', (req, res, next) => {
21
+    let { token } = req.query
22
+    if (token) res.cookie('auth_token', token)
23
+    if (!registered) {
24
+      registered = true
25
+      let proto = req.get('X-Forwarded-Proto') || req.protocol || 'http'
26
+      let baseUrl = `${proto}://${req.get('host')}`
27
+      passport.use('steam', new SteamStrategy({
28
+        returnURL: baseUrl + '/api/auth/steam/return',
29
+        realm: baseUrl,
30
+        apiKey: process.env.STEAM_KEY,
31
+        passReqToCallback: true,
32
+        profile: false
33
+      }, (req, identifier, profile, done) => {
34
+        let [ steamId ] = identifier.split('/').slice(-1)
35
+        let user = null
36
+        let token = req.cookies.auth_token
37
+        if (token) user = authlib.checkToken(token)
38
+        steamFindOrCreateUser(user, steamId)
39
+          .then(user => done(null, user))
40
+          .catch(err => done(err))
41
+      }))
42
+    }
43
+    setTimeout(next, 100)
44
+  }, passport.authenticate('steam'))
45
+
46
+  app.get('/return', passport.authenticate('steam', { failureRedirect: '/' }), (req, res) => {
47
+    res.clearCookie('auth_token')
48
+    authlib.genToken(req.user._id)
49
+      .then(token => {
50
+        let json = JSON.stringify({ username: req.user.username, token, steamid: req.user.steam.id })
51
+        res.end(`<html><body><script type="text/javascript">opener.postMessage(JSON.stringify(${json}), '*');window.close();</script></body>`)
52
+      })
53
+  })
54
+    // })
55
+  config.auth.router.use('/api/auth/steam', app)
56
+
57
+  function steamFindOrCreateUser(user, steamId) {
58
+    let { db, env } = config.common.storage
59
+    if (user) {
60
+      return user.then((user)=>{
61
+        return db.users.update({ _id: user._id }, { $set: { steam: { id: steamId }}})
62
+          .then(()=>user)
63
+      })
64
+    }
65
+    return db.users.findOne({ 'steam.id': steamId })
66
+      .then((user) => {
67
+        if (user) return user
68
+        user = {
69
+          steam: { id: steamId },
70
+          cpu: 100,
71
+          cpuAvailable: 0,
72
+          registeredDate: new Date(),
73
+          credits: 0,
74
+          gcl: 0
75
+        };
76
+        return db.users.insert(user)
77
+          .then(result => {
78
+            user = result;
79
+            return db['users.code'].insert({
80
+              user: user._id,
81
+              modules: {main: ''},
82
+              branch: 'default',
83
+              activeWorld: true,
84
+              activeSim: true
85
+            })
86
+          })
87
+          .then(() => env.set('scrUserMemory:'+user._id, JSON.stringify({})))
88
+          .then(() => user)
89
+      })
90
+  }
91
+}

BIN
out.gif View File


+ 5
- 3
package.json View File

@@ -5,12 +5,12 @@
5 5
   "main": "index.js",
6 6
   "scripts": {
7 7
     "test": "echo \"Error: no test specified\" && exit 0",
8
-    "2npm":"publish"
8
+    "2npm": "publish"
9 9
   },
10 10
   "devDependencies": {
11 11
     "publish": "^0.6.0"
12 12
   },
13
-  "screeps_mod":true,
13
+  "screeps_mod": true,
14 14
   "keywords": [
15 15
     "screeps",
16 16
     "mod"
@@ -20,9 +20,11 @@
20 20
   "dependencies": {
21 21
     "basic-auth": "^1.0.4",
22 22
     "body-parser": "^1.15.2",
23
+    "cookie-parser": "^1.4.3",
23 24
     "express": "^4.14.0",
24 25
     "passport": "^0.3.2",
25 26
     "passport-http": "^0.3.0",
26
-    "passport-local": "^1.0.0"
27
+    "passport-local": "^1.0.0",
28
+    "passport-steam": "^1.0.8"
27 29
   }
28 30
 }

+ 1717
- 0
yarn.lock
File diff suppressed because it is too large
View File