<commit_before>const express = require('express')
const bodyParser = require('body-parser')
const compression = require('compression')
const path = require('path')
const emojiFavicon = require('emoji-favicon')
const uuid = require('uuid')
const AWS = require('aws-sdk')
const morgan = require('morgan')
const _ = require('lodash')
const jwt = require('express-jwt')
const AuthenticationClient = require('auth0').AuthenticationClient
const jwks = require('jwks-rsa')

const Promise = require('bluebird')
const multiparty = Promise.promisifyAll(require('multiparty'), {multiArgs: true})
const fs = Promise.promisifyAll(require('fs'))

const models = require('./models')
const utils = require('./utils')

const app = express()
app.use(bodyParser.json())
app.use(compression())
app.use(emojiFavicon('sparkles'))
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'))

app.use(express.static(path.resolve(__dirname, '..', 'client', 'build')))

const jwtCheck = jwt({
  secret: jwks.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: 'https://twobucks.auth0.com/.well-known/jwks.json'
  }),
  audience: 'https://localhost:3000',
  issuer: 'https://twobucks.auth0.com/',
  algorithms: ['RS256']
})

const auth0 = new AuthenticationClient({
  domain: 'twobucks.auth0.com'
})

app.post('/api/login', jwtCheck, async (req, res) => {
  try {
    const authToken = utils.getJWTToken(req)
    const userInfoRaw = await auth0.users.getInfo(authToken)
    const userInfo = JSON.parse(userInfoRaw)
    const where = utils.whereQueryFromUserInfo(userInfo)
    const accessToken = uuid.v4()
    const [ user ] = await models.User.findOrCreate({
      where,
      defaults: { auth_token: authToken, access_token: accessToken }
    })
    await user.update({ auth_token: authToken })
    res.json(_.pick(user, 'auth_token'))
  } catch (e) {
    console.log(e)
  }
})

app.get('/api/tokens', jwtCheck, async (req, res) => {
  const token = utils.getJWTToken(req)
  const user = await models.User.findOne({
    where: {
      auth_token: token
    }
  })

  if (!user) {
    res.status(404).json({
      error: 'User not found'
    })
    return
  }

  res.json(_.pick(user, 's3_details', 'access_token'))
})

app.post('/api/test', jwtCheck, async (req, res) => {
  try {
    const token = utils.getJWTToken(req)
    const user = await models.User.findOne({
      where: {
        auth_token: token
      }
    })
    user.update({
      s3_details: {
        bucket_name: req.body.bucket_name,
        aws_secret_key: req.body.aws_secret_key,
        aws_access_key: req.body.aws_access_key
      }
    })
    const bucketName = req.body.bucket_name
    const awsSecretKey = req.body.aws_secret_key
    const awsAccessKey = req.body.aws_access_key
    const s3 = new AWS.S3({
      accessKeyId: awsAccessKey,
      secretAccessKey: awsSecretKey
    })
    Promise.promisifyAll(Object.getPrototypeOf(s3))

    const Bucket = bucketName
    const id = uuid.v4()
    const filePath = path.join(__dirname, '..', 'test', 'cat.jpg')

    const params = { Bucket, Key: id, Body: fs.createReadStream(filePath) }

    await s3.createBucketAsync({ Bucket })
    await s3.putObjectAsync(params)
    await s3.deleteObjectAsync(_.omit(params, 'Body'))
<commit_msg>move finding user to middleware<commit_after>const express = require('express')
const bodyParser = require('body-parser')
const compression = require('compression')
const path = require('path')
const emojiFavicon = require('emoji-favicon')
const uuid = require('uuid')
const AWS = require('aws-sdk')
const morgan = require('morgan')
const _ = require('lodash')
const jwt = require('express-jwt')
const AuthenticationClient = require('auth0').AuthenticationClient
const jwks = require('jwks-rsa')

const Promise = require('bluebird')
const multiparty = Promise.promisifyAll(require('multiparty'), {multiArgs: true})
const fs = Promise.promisifyAll(require('fs'))

const models = require('./models')
const utils = require('./utils')

const app = express()
app.use(bodyParser.json())
app.use(compression())
app.use(emojiFavicon('sparkles'))
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'))

app.use(express.static(path.resolve(__dirname, '..', 'client', 'build')))

const jwtCheck = jwt({
  secret: jwks.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: 'https://twobucks.auth0.com/.well-known/jwks.json'
  }),
  audience: 'https://localhost:3000',
  issuer: 'https://twobucks.auth0.com/',
  algorithms: ['RS256']
})

const auth0 = new AuthenticationClient({
  domain: 'twobucks.auth0.com'
})

app.post('/api/login', jwtCheck, async (req, res) => {
  try {
    const authToken = utils.getJWTToken(req)
    const userInfoRaw = await auth0.users.getInfo(authToken)
    const userInfo = JSON.parse(userInfoRaw)
    const where = utils.whereQueryFromUserInfo(userInfo)
    const accessToken = uuid.v4()
    const [ user ] = await models.User.findOrCreate({
      where,
      defaults: { auth_token: authToken, access_token: accessToken }
    })
    await user.update({ auth_token: authToken })
    res.json(_.pick(user, 'auth_token'))
  } catch (e) {
    console.log(e)
  }
})

async function findUser (req, res, next) {
  const token = utils.getJWTToken(req)
  const user = await models.User.findOne({
    where: {
      auth_token: token
    }
  })

  req.user = user
  next()
}

app.get('/api/tokens', jwtCheck, findUser, async (req, res) => {
  if (!req.user) {
    res.status(404).json({
      error: 'User not found'
    })
    return
  }

  res.json(_.pick(req.user, 's3_details', 'access_token'))
})

app.post('/api/test', jwtCheck, findUser, async (req, res) => {
  try {
    req.user.update({
      s3_details: {
        bucket_name: req.body.bucket_name,
        aws_secret_key: req.body.aws_secret_key,
        aws_access_key: req.body.aws_access_key
      }
    })
    const bucketName = req.body.bucket_name
    const awsSecretKey = req.body.aws_secret_key
    const awsAccessKey = req.body.aws_access_key
    const s3 = new AWS.S3({
      accessKeyId: awsAccessKey,
      secretAccessKey: awsSecretKey
    })
    Promise.promisifyAll(Object.getPrototypeOf(s3))

    const Bucket = bucketName
    const id = uuid.v4()
    const filePath = path.join(__dirname, '..', 'test', 'cat.jpg')

    const params = { Bucket, Key: id, Body: fs.createReadStream(filePath) }

    await s3.createBucketAsync({ Bucket })
    await s3.putObjectAsync(params)
    await s3.deleteObjectAsync(_.omit(params, 'Body'))

{'fraction_non_alphanumeric': 0.14926262475793237, 'fraction_numerical': 0.00804409354982869, 'mean_word_length': 3.858176555716353, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5582725', 'n_tokens_mistral': 2294, 'n_tokens_neox': 2299, 'n_words': 467}