Skip to content

Commit

Permalink
feat: add jwt metod
Browse files Browse the repository at this point in the history
  • Loading branch information
agus-darmawan committed Dec 8, 2024
1 parent ec3d9b0 commit 2c9f917
Show file tree
Hide file tree
Showing 14 changed files with 97 additions and 263 deletions.
34 changes: 3 additions & 31 deletions app/controllers/auth_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import VerifyEmailNotification from '#mails/verify_email_notification'
import ResetPasswordNotification from '#mails/reset_password_notification'
import AuthValidator from '#validators/auth'
import messagesProvider from '#helpers/validation_messages_provider'
import { UUID } from 'node:crypto'

export default class AuthController {
async login({ request, response }: HttpContext) {
async login({ request, response, auth }: HttpContext) {
const data = await vine
.compile(AuthValidator.loginSchema)
.validate(request.all(), { messagesProvider })
Expand All @@ -20,20 +19,9 @@ export default class AuthController {
data.email = `${data.email}@student.its.ac.id`
}
const user = await User.verifyCredentials(data.email, data.password)
const token = await User.accessTokens.create(user, ['*'], { expiresIn: '1 days' })
const token = await auth.use('jwt').generate(user)

if (!token.value!.release()) {
return response.unprocessableEntity({
success: false,
message: 'Invalid email or password.',
})
}

return response.ok({
success: true,
message: 'Login successful.',
data: token.value!.release(),
})
return response.ok({ token })
} catch (error) {
return response.unprocessableEntity({
success: false,
Expand Down Expand Up @@ -88,22 +76,6 @@ export default class AuthController {
}
}

async logout({ auth, response }: HttpContext) {
try {
await User.accessTokens.delete(auth.user!, auth.user!.currentAccessToken.identifier)
return response.ok({
success: true,
message: 'Logged out successfully.',
})
} catch (error) {
return response.internalServerError({
success: false,
message: 'Logout failed.',
error: error.message,
})
}
}

async verifyEmail({ params, request, response }: HttpContext) {
try {
if (!request.hasValidSignature()) {
Expand Down
161 changes: 0 additions & 161 deletions app/controllers/files_controller.ts

This file was deleted.

8 changes: 4 additions & 4 deletions app/controllers/oauth_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export default class OauthController {
}
}

async token({ request, response }: HttpContext) {
async token({ request, response, auth }: HttpContext) {
const {
grant_type: grantType,
code,
Expand Down Expand Up @@ -174,8 +174,8 @@ export default class OauthController {

try {
await authCode.delete()
const token = await User.accessTokens.create(user, ['*'], { expiresIn: '1 days' })
if (!token.value!.release()) {
const token = await auth.use('jwt').generate(user)
if (!token) {
return response.unprocessableEntity({
success: false,
message: 'Failed to generate access token.',
Expand All @@ -186,7 +186,7 @@ export default class OauthController {
success: true,
message: 'Login successful.',
data: {
token: token.value!.release(),
token: token,
state: authCode.state,
nonce: authCode.nonce,
},
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/user_profiles_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import messagesProvider from '#helpers/validation_messages_provider'
export default class UserProfilesController {
async store({ auth, request, response }: HttpContext) {
const user = await auth.authenticate()
const userId = user.currentAccessToken.tokenableId
const userId = user.id

const data = await vine
.compile(UserProfileValidator.createSchema)
Expand Down
31 changes: 31 additions & 0 deletions app/middleware/guest_middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'
import type { Authenticators } from '@adonisjs/auth/types'

/**
* Guest middleware is used to deny access to routes that should
* be accessed by unauthenticated users.
*
* For example, the login page should not be accessible if the user
* is already logged-in
*/
export default class GuestMiddleware {
/**
* The URL to redirect to when user is logged-in
*/
redirectTo = '/'

async handle(
ctx: HttpContext,
next: NextFn,
options: { guards?: (keyof Authenticators)[] } = {}
) {
for (let guard of options.guards || [ctx.auth.defaultGuard]) {
if (await ctx.auth.use(guard).check()) {
return ctx.response.redirect(this.redirectTo, true)
}
}

return next()
}
}
23 changes: 17 additions & 6 deletions config/auth.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
import { defineConfig } from '@adonisjs/auth'
import { tokensGuard, tokensUserProvider } from '@adonisjs/auth/access_tokens'
import type { InferAuthEvents, Authenticators as AuthType } from '@adonisjs/auth/types'
import { jwtGuard } from '@maximemrf/adonisjs-jwt/jwt_config'
import { sessionGuard, sessionUserProvider } from '@adonisjs/auth/session'

const authConfig = defineConfig({
default: 'api',
default: 'jwt',
guards: {
api: tokensGuard({
provider: tokensUserProvider({
tokens: 'accessTokens',
web: sessionGuard({
useRememberMeTokens: false,
provider: sessionUserProvider({
model: () => import('#models/user'),
}),
}),
jwt: jwtGuard({
tokenExpiresIn: '1h',
useCookies: false,
provider: sessionUserProvider({
model: () => import('#models/user'),
}),
content: (user: any) => ({
userId: user.getId(),
email: user.getOriginal().email,
}),
}),
},
})

export default authConfig

/**
* Inferring types from the configured auth
* guards.
Expand Down
31 changes: 0 additions & 31 deletions database/migrations/1720002752107_create_access_tokens_table.ts

This file was deleted.

20 changes: 20 additions & 0 deletions database/migrations/1733638777895_create_users_table.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { BaseSchema } from '@adonisjs/lucid/schema'

export default class extends BaseSchema {
protected tableName = 'users'

async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id').notNullable()
table.string('full_name').nullable()
table.string('email', 254).notNullable().unique()
table.string('password').notNullable()
table.timestamp('created_at').notNullable()
table.timestamp('updated_at').nullable()
})
}

async down() {
this.schema.dropTable(this.tableName)
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"@adonisjs/cors": "^2.2.1",
"@adonisjs/lucid": "^21.1.0",
"@adonisjs/mail": "^9.2.2",
"@maximemrf/adonisjs-jwt": "^0.2.2",
"@types/jsonwebtoken": "^9.0.7",
"@vinejs/vine": "^2.1.0",
"edge.js": "^6.0.2",
Expand Down
Loading

0 comments on commit 2c9f917

Please sign in to comment.