Skip to content

Commit

Permalink
feat: add logout module
Browse files Browse the repository at this point in the history
  • Loading branch information
DeVoresyah committed Dec 29, 2023
1 parent 6fd78e5 commit 26a9b62
Show file tree
Hide file tree
Showing 11 changed files with 79 additions and 12 deletions.
53 changes: 50 additions & 3 deletions app/Controllers/Http/v1/Auth/AuthsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import TwilioService from 'App/Services/TwilioService'
import RegisterWithPasswordValidator from 'App/Validators/v1/Auth/RegisterWithPasswordValidator'
import LoginWithPasswordValidator from 'App/Validators/v1/Auth/LoginWithPasswordValidator'
import LoginWithOtpValidator from 'App/Validators/v1/Auth/LoginWithOtpValidator'
import LogoutValidator from 'App/Validators/v1/Auth/LogoutValidator'

// Models
import User from 'App/Models/User'
Expand Down Expand Up @@ -204,7 +205,9 @@ export default class AuthsController {
})

if (newSession.session && newSession.refreshToken) {
const userToken = this.jwt.generate({ user_id: user.id }).make()
const userToken = this.jwt
.generate({ user_id: user.id, session_id: newSession.session.id })
.make()
const expiresAt = DateTime.now().plus({ days: 7 }).toUnixInteger()

return response.api(
Expand Down Expand Up @@ -243,8 +246,6 @@ export default class AuthsController {
return response.api({ message: 'Invalid credentials.' }, StatusCodes.UNAUTHORIZED)
}

console.log(user.toJSON())

if (payload.email && !user.emailConfirmedAt) {
return response.api({ message: 'Please confirm your email.' }, StatusCodes.FORBIDDEN)
}
Expand Down Expand Up @@ -293,4 +294,50 @@ export default class AuthsController {
return response.api({ message: `OTP Code has been sent to ${payload.phone}` }, StatusCodes.OK)
}
}

public async signOut({ request, response }: HttpContextContract) {
const payload = await request.validate(LogoutValidator)
const userId = request.decoded!.user_id
const sessionId = request.decoded!.session_id

const sessions = await Database.transaction(async (trx) => {
const currentSession = await Session.query({ client: trx })
.where('user_id', userId)
.andWhere('id', sessionId)
.first()

const allSession = await Session.query({ client: trx }).where('user_id', userId).exec()

return {
currentSession,
allSession,
}
})

try {
if (!sessions.currentSession) {
return response.api({ message: 'Invalid session.' }, StatusCodes.UNAUTHORIZED)
}

if (payload.scope === 'global') {
sessions.allSession.map(async (session) => {
await session.delete()
})
}

if (payload.scope === 'others') {
sessions.allSession.map(async (session) => {
if (session.id !== sessions.currentSession!.id) await session.delete()
})
}

if (payload.scope === 'local') {
await sessions.currentSession.delete()
}

return response.api({ message: '' }, StatusCodes.NO_CONTENT)
} catch (e) {
return response.api({ message: `704: ${e}` }, StatusCodes.INTERNAL_SERVER_ERROR)
}
}
}
8 changes: 6 additions & 2 deletions app/Controllers/Http/v1/Auth/VerifiesController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,9 @@ export default class VerifiesController {
})

if (newSession.session && newSession.refreshToken) {
const userToken = this.jwt.generate({ user_id: user.id }).make()
const userToken = this.jwt
.generate({ user_id: user.id, session_id: newSession.session.id })
.make()
const expiresAt = DateTime.now().plus({ days: 7 }).toUnixInteger()

return response.api(
Expand Down Expand Up @@ -230,7 +232,9 @@ export default class VerifiesController {
})

if (newSession.session && newSession.refreshToken) {
const userToken = this.jwt.generate({ user_id: user.id }).make()
const userToken = this.jwt
.generate({ user_id: user.id, session_id: newSession.session.id })
.make()
const expiresAt = DateTime.now().plus({ days: 7 }).toUnixInteger()

return response
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import JwtService from 'App/Services/JwtService'

export default class SessionMiddleware {
export default class UserSessionMiddleware {
public jwtService = new JwtService()

public async handle({ request, response }: HttpContextContract, next: () => Promise<void>) {
Expand All @@ -20,6 +20,7 @@ export default class SessionMiddleware {

request.decoded = {
user_id: decoded['user_id'],
session_id: decoded['session_id'],
}

await next()
Expand Down
1 change: 1 addition & 0 deletions app/Types/authentication.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
interface Token {
user_id: string
session_id: string
}

interface JwtGeneratePayload {
Expand Down
12 changes: 12 additions & 0 deletions app/Validators/v1/Auth/LogoutValidator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { schema, CustomMessages } from '@ioc:Adonis/Core/Validator'
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class LogoutValidator {
constructor(protected ctx: HttpContextContract) {}

public schema = schema.create({
scope: schema.enum(['global', 'local', 'others']),
})

public messages: CustomMessages = {}
}
3 changes: 2 additions & 1 deletion contracts/request.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
interface Token {
user_id: number
user_id: string
session_id: string
}

declare module '@ioc:Adonis/Core/Request' {
Expand Down
2 changes: 1 addition & 1 deletion database/migrations/1702736652259_identities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default class extends BaseSchema {
table
.uuid('id', { primaryKey: true })
.defaultTo(this.db.rawQuery('uuid_generate_v4()').knexQuery)
table.uuid('user_id').references('id').inTable('auth.users')
table.uuid('user_id').references('id').inTable('auth.users').onDelete('CASCADE')
table.string('provider')
table.jsonb('identity_data')
table.timestamp('last_sign_in_at', { useTz: true })
Expand Down
2 changes: 1 addition & 1 deletion database/migrations/1702737214080_sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default class extends BaseSchema {
table
.uuid('id', { primaryKey: true })
.defaultTo(this.db.rawQuery('uuid_generate_v4()').knexQuery)
table.uuid('user_id').references('id').inTable('auth.users')
table.uuid('user_id').references('id').inTable('auth.users').onDelete('CASCADE')
table.timestamp('refreshed_at', { useTz: true })
table.text('user_agent')
table.string('ip')
Expand Down
4 changes: 2 additions & 2 deletions database/migrations/1702737445458_refresh_tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ export default class extends BaseSchema {
public async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
table.uuid('user_id').references('id').inTable('auth.users')
table.uuid('session_id').references('id').inTable('auth.sessions')
table.uuid('user_id').references('id').inTable('auth.users').onDelete('CASCADE')
table.uuid('session_id').references('id').inTable('auth.sessions').onDelete('CASCADE')
table.string('token')
table.boolean('revoked').defaultTo(false)
table.string('parent').nullable()
Expand Down
1 change: 1 addition & 0 deletions routes/auth/v1/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Route.group(() => {
Route.post('/register', 'AuthsController.signUpWithPassword')
Route.post('/login/password', 'AuthsController.signInWithPassword')
Route.post('/login/otp', 'AuthsController.signInWithOtp')
Route.delete('/logout', 'AuthsController.signOut').middleware('userSession')
require('./verify')
})
.prefix('/v1')
Expand Down
2 changes: 1 addition & 1 deletion start/kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,5 @@ Server.middleware.register([
|
*/
Server.middleware.registerNamed({
session: () => import('App/Middleware/SessionMiddleware'),
userSession: () => import('App/Middleware/UserSessionMiddleware'),
})

0 comments on commit 26a9b62

Please sign in to comment.