Skip to content

Commit

Permalink
Fix/refresh token mechanism
Browse files Browse the repository at this point in the history
  • Loading branch information
Courtcircuits committed Nov 7, 2024
1 parent 51b0095 commit 723737c
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
12 changes: 11 additions & 1 deletion apps/authentication/controllers/authentication_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ export default class AuthenticationController {
message: 'update user connected',
})

response.cookie('beep.access_token', tokens.accessToken)
response.cookie('beep.refresh_token', tokens.refreshToken)

return response.send({
user,
tokens,
Expand Down Expand Up @@ -86,7 +89,11 @@ export default class AuthenticationController {
}

async refresh({ response, request, auth }: HttpContext) {
const { refreshToken } = request.only(['refreshToken'])
let { refreshToken } = request.only(['refreshToken'])

if (!refreshToken) {
refreshToken = request.cookie('beep.refresh_token')
}

const payload = await this.authenticationService.verifyToken(refreshToken)

Expand All @@ -107,6 +114,9 @@ export default class AuthenticationController {

const tokens = await auth.use('jwt').generate(user)

response.cookie('beep.access_token', tokens.accessToken)
response.cookie('beep.refresh_token', tokens.refreshToken)

return response.send({
...tokens,
})
Expand Down
2 changes: 1 addition & 1 deletion apps/shared/middleware/auth_middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default class AuthMiddleware {
/**
* The URL to redirect to, when authentication fails
*/
redirectTo = '/login'
redirectTo = '/authentication/signin'

async userIsAudited(jwt: JwtPayloadContract) {
if (!jwt.audited_account) {
Expand Down
13 changes: 13 additions & 0 deletions apps/shared/middleware/set_authorization_middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { HttpContext } from '@adonisjs/core/http'

export default class SetAuthorizationHeader {
async handle({ request }: HttpContext, next: () => Promise<void>) {
const token = request.cookie('beep.access_token')

if (token) {
request.headers().authorization = `Bearer ${token}`
}

await next()
}
}
1 change: 1 addition & 0 deletions start/kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ server.errorHandler(() => import('#apps/shared/exceptions/handler'))
server.use([
() => import('#apps/shared/middleware/container_bindings_middleware'),
() => import('#apps/shared/middleware/force_json_response_middleware'),
() => import('#apps/shared/middleware/set_authorization_middleware'),
() => import('@adonisjs/cors/cors_middleware'),
])

Expand Down

0 comments on commit 723737c

Please sign in to comment.