feat: graphql auto refresh token + apollo improvements

This commit is contained in:
NGPixel
2023-05-30 04:42:37 +00:00
parent e9fc514c92
commit eed3675512
12 changed files with 183 additions and 41 deletions
+34
View File
@@ -1,5 +1,8 @@
import _ from 'lodash-es'
import { generateError, generateSuccess } from '../../helpers/graph.mjs'
import jwt from 'jsonwebtoken'
import ms from 'ms'
import { DateTime } from 'luxon'
export default {
Query: {
@@ -148,6 +151,37 @@ export default {
return generateError(err)
}
},
/**
* Refresh Token
*/
async refreshToken (obj, args, context) {
try {
let decoded = {}
if (!args.token) {
throw new Error('ERR_MISSING_TOKEN')
}
try {
decoded = jwt.verify(args.token, WIKI.config.auth.certs.public, {
audience: WIKI.config.auth.audience,
issuer: 'urn:wiki.js',
algorithms: ['RS256'],
ignoreExpiration: true
})
} catch (err) {
throw new Error('ERR_INVALID_TOKEN')
}
if (DateTime.utc().minus(ms(WIKI.config.auth.tokenRenewal)) > DateTime.fromSeconds(decoded.exp)) {
throw new Error('ERR_EXPIRED_TOKEN')
}
const newToken = await WIKI.db.users.refreshToken(decoded.id)
return {
jwt: newToken.token,
operation: generateSuccess('Token refreshed successfully')
}
} catch (err) {
return generateError(err)
}
},
/**
* Set API state
*/
@@ -58,6 +58,10 @@ extend type Mutation {
name: String!
): AuthenticationRegisterResponse
refreshToken(
token: String!
): AuthenticationTokenResponse @rateLimit(limit: 30, duration: 60)
revokeApiKey(
id: UUID!
): DefaultResponse
@@ -128,6 +132,11 @@ type AuthenticationRegisterResponse {
jwt: String
}
type AuthenticationTokenResponse {
operation: Operation
jwt: String
}
input AuthenticationStrategyInput {
key: String!
strategyKey: String!