summaryrefslogtreecommitdiff
path: root/lib/response.js
blob: 4d22d563dec41e3b74b0430d936cf21cea616d2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
'use strict'
// response
// external modules
const fs = require('fs')
const path = require('path')
const fetch = require('node-fetch')
// core
const config = require('./config')
const logger = require('./logger')
const models = require('./models')
const noteUtil = require('./web/note/util')
const errors = require('./errors')

// public
const response = {
  showIndex: showIndex,
  githubActions: githubActions,
  gitlabActions: gitlabActions
}

function showIndex (req, res, next) {
  const authStatus = req.isAuthenticated()
  const deleteToken = ''

  const data = {
    signin: authStatus,
    infoMessage: req.flash('info'),
    errorMessage: req.flash('error'),
    imprint: fs.existsSync(path.join(config.docsPath, 'imprint.md')),
    privacyStatement: fs.existsSync(path.join(config.docsPath, 'privacy.md')),
    termsOfUse: fs.existsSync(path.join(config.docsPath, 'terms-of-use.md')),
    deleteToken: deleteToken
  }

  if (authStatus) {
    models.User.findOne({
      where: {
        id: req.user.id
      }
    }).then(function (user) {
      if (user) {
        data.deleteToken = user.deleteToken
        res.render('index.ejs', data)
      }
    })
  } else {
    res.render('index.ejs', data)
  }
}

function githubActions (req, res, next) {
  const noteId = req.params.noteId
  noteUtil.findNote(req, res, function (note) {
    const action = req.params.action
    switch (action) {
      case 'gist':
        githubActionGist(req, res, note)
        break
      default:
        res.redirect(config.serverURL + '/' + noteId)
        break
    }
  })
}

function githubActionGist (req, res, note) {
  const code = req.query.code
  const state = req.query.state
  if (!code || !state) {
    return errors.errorForbidden(res)
  } else {
    const data = {
      client_id: config.github.clientID,
      client_secret: config.github.clientSecret,
      code: code,
      state: state
    }
    const authUrl = 'https://github.com/login/oauth/access_token'
    fetch(authUrl, {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json'
      }
    }).then(resp => {
      if (!resp.ok) {
        throw new Error('forbidden')
      }
      return resp.json()
    }).then(body => {
      const accessToken = body.access_token
      if (!accessToken) {
        throw new Error('forbidden')
      }
      const content = note.content
      const title = models.Note.decodeTitle(note.title)
      const filename = title.replace('/', ' ') + '.md'
      const gist = {
        files: {}
      }
      gist.files[filename] = {
        content: content
      }
      const gistUrl = 'https://api.github.com/gists'
      return fetch(gistUrl, {
        method: 'POST',
        body: JSON.stringify(gist),
        headers: {
          'User-Agent': 'HedgeDoc',
          Authorization: 'token ' + accessToken,
          'Content-Type': 'application/json',
          Accept: 'application/json'
        }
      })
    }).then(resp => {
      if (resp.status !== 201) {
        throw new Error('forbidden')
      }
      return resp.json()
    }).then(body => {
      res.setHeader('referer', '')
      res.redirect(body.html_url)
    }).catch(error => {
      if (error.message === 'forbidden') {
        return errors.errorForbidden(res)
      }
      logger.error('GitHub Gist auth failed: ' + error)
      return errors.errorInternalError(res)
    })
  }
}

function gitlabActions (req, res, next) {
  const noteId = req.params.noteId
  noteUtil.findNote(req, res, function (note) {
    const action = req.params.action
    switch (action) {
      case 'projects':
        gitlabActionProjects(req, res, note)
        break
      default:
        res.redirect(config.serverURL + '/' + noteId)
        break
    }
  })
}

function gitlabActionProjects (req, res, note) {
  if (req.isAuthenticated()) {
    models.User.findOne({
      where: {
        id: req.user.id
      }
    }).then(function (user) {
      if (!user) { return errors.errorNotFound(res) }
      const ret = { baseURL: config.gitlab.baseURL, version: config.gitlab.version }
      ret.accesstoken = user.accessToken
      ret.profileid = user.profileid
      const apiUrl = `${config.gitlab.baseURL}/api/${config.gitlab.version}/projects?membership=yes&per_page=100&access_token=${user.accessToken}`
      fetch(apiUrl).then(resp => {
        if (!resp.ok) {
          res.send(ret)
          throw new Error('HTTP request returned not okay-ish status')
        }
        return resp.json()
      }).then(body => {
        ret.projects = body
        return res.send(ret)
      })
    }).catch(function (err) {
      logger.error('gitlab action projects failed: ' + err)
      return errors.errorInternalError(res)
    })
  } else {
    return errors.errorForbidden(res)
  }
}

module.exports = response