Skip to content
Snippets Groups Projects
Verified Commit 3d3025a8 authored by Louis's avatar Louis :fire:
Browse files

Move sentry init to vendor folder

parent 474db874
No related branches found
No related tags found
No related merge requests found
......@@ -15,13 +15,8 @@ let server = null
let worker = null
function bindSentry(app) {
Sentry.init({
dsn: config('sentry.dsn'),
integrations: integrations => integrations.filter(itg => itg.name !== 'Console'),
environment: config('app.env'),
tracesSampleRate: config('sentry.samples'),
release: `${ pkg.name }@${ pkg.version }`
})
const sentryUtil = require('vendor/sentry')
sentryUtil.configure()
debug('Binding sentry to app level errors')
......
......@@ -61,4 +61,32 @@ exports.loadKeys = async () => {
patchConfig('app.security.public_key', pub)
patchConfig('app.security.private_key', priv)
return { pub, priv }
}
exports.sign = async (payload) => {
const threadContext = require('core/injection/ThreadContext')
const { default: SignJWT } = require('jose/jwt/sign')
const { priv } = exports.getKeys()
return await threadContext.profile('jwt.sign', JSON.stringify(payload), () => new SignJWT(payload)
.setIssuer(exports.jwtOptions.issuer)
.setIssuedAt()
.setProtectedHeader({ alg: 'RS256' })
.sign(priv))
}
exports.verify = async(token) => {
const threadContext = require('core/injection/ThreadContext')
const { default: jwtVerify } = require('jose/jwt/verify')
const { getKeys, jwtOptions } = exports
const { pub } = getKeys()
return await threadContext.profile('jwt.verify', undefined, async () => {
const { payload } = await jwtVerify(token, pub, jwtOptions)
return payload
})
}
exports.jwtOptions = {
issuer: 'urn:jetsam:systems:auth',
}
\ No newline at end of file
......@@ -22,10 +22,47 @@ class User extends BaseModel {
})
}
static async fromToken(token) {
static async fromToken(token, type) {
const HttpError = require('core/errors/HttpError')
let id = null
if (type) {
switch (type) {
case 'jwt':
id = await this.idFromJwt(token)
break
case 'opaque':
default:
id = await this.idFromOpaque(token)
break
}
} else {
try {
id = await this.idFromOpaque(token)
} catch(e) {}
if (id == null) {
try {
id = await this.idFromJwt(token)
} catch(e) {}
}
}
if (id == null) {
throw new HttpError(401, 'No valid token was provided')
}
return User.findOne({ where: { id } })
}
static async idFromJwt(token) {
const { verify } = require('core/utils/jwt')
const payload = await verify(token)
return payload.session.id
}
static async idFromOpaque(token) {
const crypto = require('core/utils/crypto')
const { session } = JSON.parse(await crypto.decrypt(token))
return User.findOne({ where: { id: session } })
return session
}
static async getSystemUser() {
......@@ -57,23 +94,38 @@ class User extends BaseModel {
return this
}
async asToken() {
async asToken(type = 'opaque') {
switch (type) {
case 'jwt':
return this.asJWTToken()
case 'opaque':
default:
return this.asOpaqueToken()
}
}
async asOpaqueToken() {
const crypto = require('core/utils/crypto')
console.log(this.id)
return await crypto.encrypt(JSON.stringify({ session: this.id }))
}
async asJWTToken() {
const { sign } = require('core/utils/jwt')
return await sign({
session: {
id: this.id,
roles: ['overseer', 'user'],
},
})
}
async checkPassword(password) {
const crypto = require('core/utils/crypto')
if (this.password == null) {
return false
}
console.log("CHECKING", password)
const b = await crypto.verify(this.password, password)
console.log("HAS DVERIFIFIED", b)
return b
}
......
......@@ -17,20 +17,20 @@ exports.register = async ctx => {
throw new HttpError(409, 'Email Already Exists', { status: 409, title: 'Email Already Exists', description: 'That email address already exists. Please try another email address.' })
}
const newUser = await ctx.services['core.users'].register(name ?? null, email, password)
const newUser = await ctx.services['core.users']
.register(name ?? null, email, password)
await newUser.handleIncludes(ctx.includes)
const token = await newUser.asToken()
const token = await newUser.asToken(ctx.get('x-token-type'))
ctx.body = { user: newUser, token }
}
exports.login = async ctx => {
const { email, password } = ctx.request.body
console.log("LOGGING IN")
const user = await ctx.services['core.auth'].attemptLogin(email, password)
console.log("LOGGING IN 222")
const user = await ctx.services['core.auth']
.attemptLogin(email, password)
const token = await user.asToken()
const token = await user.asToken(ctx.get('x-token-type'))
ctx.body = { token }
}
......@@ -45,38 +45,6 @@ exports.triggerPasswordReset = async ctx => {
await queue.dispatch('send-user-password-reset', { email })
// const token = await ctx.profile('user.generateResetToken', 'Create reset token', () => user.generateResetToken())
//
// const name = user.name || 'Jetsam User (You haven\'t told us your name!)'
// const reset_link = new URL(`/reset-password?token=${ token }`, config('app.host.web'))
//
// const { mail } = require('services')
//
// try {
// await ctx.profile(
// 'services.mail.sendTemplate',
// `template ${ config('mail.templates.reset-password')}`,
// () => mail.sendTemplate(email, 'Reset Your Jetsam password', config('mail.templates.reset-password'), {
// name,
// reset_link,
// })
// )
// } catch (e) {
// // reporter.report(e)
// console.log(e.response.body.errors)
// throw new HttpError(
// 500,
// 'Failed To Send Reset Email',
// { status: 500, title: 'Failed to send reset email', description: 'Could not send the password reset email' },
// {
// sendgrid: (e.response?.body?.errors ?? []).reduce((acc, e, i) => ({
// ...acc,
// [`err-${ i }`]: JSON.stringify(e, null, 2),
// }), {}),
// }
// )
// }
ctx.body = {
reset_token: null,
}
......
......@@ -49,14 +49,14 @@ security.get('/jwks', async ctx => {
const { default: fromKeyLike } = require('jose/jwk/from_key_like')
const jwk = await fromKeyLike(pub)
// RS256
ctx.set('Cache-Control', `public, max-age=30`)
ctx.body = {
keys: [{
use: 'sig',
...jwk
...jwk,
alg: 'RS256',
}],
}
})
......
const Sentry = require('@sentry/node')
const Tracing = require('@sentry/tracing')
const blockedPaths = new Set([
'/api/.secure/jwks',
'/api',
])
exports.configure = function() {
const pkg = require('../../package.json')
const { config } = require('bootstrap')
Sentry.init({
dsn: config('sentry.dsn'),
integrations: integrations => integrations.filter(itg => itg.name !== 'Console'),
environment: config('app.env'),
release: `${ pkg.name }@${ pkg.version }`,
tracesSampler: (ctx) => {
if (
ctx.transactionContext?.op === 'http.request'
&& blockedPaths.has(ctx.transactionContext?.tags?.['http.path'])
) {
return 0
}
return config('sentry.samples')
},
})
}
\ No newline at end of file
......@@ -30,14 +30,8 @@ async function main() {
}
function bindSentry() {
Sentry.init({
dsn: config('sentry.dsn'),
integrations: integrations => integrations.filter(itg => itg.name !== 'Console'),
environment: config('app.env'),
tracesSampleRate: config('sentry.samples'),
release: `${ pkg.name }@${ pkg.version }`
})
const sentryUtil = require('vendor/sentry')
sentryUtil.configure()
debug('Binding sentry to process level errors')
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment