Skip to content

Instantly share code, notes, and snippets.

@nicolaubrasil
Forked from jaonoctus/AuthService.ts
Created April 2, 2020 12:00
Show Gist options
  • Save nicolaubrasil/9431059b72db9805282fa5fcc158b43b to your computer and use it in GitHub Desktop.
Save nicolaubrasil/9431059b72db9805282fa5fcc158b43b to your computer and use it in GitHub Desktop.
adonisJS JWT Auth
// VueJS frontend
import ApiService from './api.service'
export type LoginCredentials = {
email: string;
password: string;
}
class AuthService {
jwt?: string
get isAuth (): boolean {
return this.jwt !== undefined
}
async check (): Promise<boolean> {
if (this.isAuth) {
return true
}
try {
await this.refresh()
return true
} catch (error) {
return false
}
}
async storeCredentials (jwt?: string): Promise<void> {
this.jwt = jwt
}
async login (credentials: LoginCredentials) {
const response = await ApiService.request.post('/auth/login', credentials, {
withCredentials: true
})
const { jwt } = response.data
await this.storeCredentials(jwt)
return response
}
async logout () {
await ApiService.request.post('/auth/logout', undefined, {
withCredentials: true
})
this.storeCredentials(undefined)
}
private async refresh (): Promise<void> {
try {
const { data } = await ApiService.request.post('/auth/refresh', undefined, {
withCredentials: true
})
await this.storeCredentials(data.jwt)
} catch (error) {
this.storeCredentials(undefined)
throw error
}
}
}
export default new AuthService()
// adonisJS backend
class LoginController {
async store ({ auth, request, response }) {
const { email, password } = request.all()
const { token: jwt, refreshToken } = await auth.withRefreshToken().attempt(email, password)
response.cookie('refreshToken', refreshToken, { httpOnly: true })
return response.ok({ jwt })
}
}
module.exports = LoginController
// adonisJS backend
class LogoutController {
async store ({ response }) {
response.clearCookie('refreshToken', { httpOnly: true })
return response.ok()
}
}
module.exports = LogoutController
// adonisJS backend
class RefreshController {
async store ({ auth, request, response }) {
const oldRefreshToken = request.cookie('refreshToken')
const { token: jwt, refreshToken } = await auth.generateForRefreshToken(oldRefreshToken)
await auth.authenticator('jwt').revokeTokens([oldRefreshToken], true)
response.cookie('refreshToken', refreshToken, { httpOnly: true })
return response.ok({ jwt })
}
}
module.exports = RefreshController
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment