Skip to content

Commit

Permalink
feat - auth session mongodb ttl
Browse files Browse the repository at this point in the history
  • Loading branch information
jaga-live committed Dec 16, 2023
1 parent a8f8d81 commit d5f1ee4
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 38 deletions.
10 changes: 7 additions & 3 deletions src/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { AuthController } from 'src/modules/auth/auth.controller';
import { Auth, AuthSchema } from 'src/modules/auth/model/auth.model';
import { AuthSessionSchema } from 'src/modules/auth/model/auth-session.model';
import { AuthService } from 'src/modules/auth/service/auth.service';
import { DiscordAuthService } from 'src/modules/auth/service/discord_auth.service';
import { UserModule } from 'src/modules/users/user.module';
Expand All @@ -15,12 +15,16 @@ import { DiscordProvider } from 'src/providers/discord.provider';
global: true,
secret: process.env.JWT_SECRET,
}),
MongooseModule.forFeature([{ name: Auth.name, schema: AuthSchema }]),
MongooseModule.forFeature([
{ name: 'auth_session', schema: AuthSessionSchema },
]),
],
controllers: [AuthController],
providers: [AuthService, DiscordAuthService, DiscordProvider],
exports: [
MongooseModule.forFeature([{ name: Auth.name, schema: AuthSchema }]),
MongooseModule.forFeature([
{ name: 'auth_session', schema: AuthSessionSchema },
]),
],
})
export class AuthModule {}
14 changes: 9 additions & 5 deletions src/modules/auth/guards/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ import {
import { JwtService } from '@nestjs/jwt';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Auth } from 'src/modules/auth/model/auth.model';
import { AuthSession } from 'src/modules/auth/model/auth-session.model';
import { Req } from 'src/types/express.types';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(
@InjectModel(Auth.name) private readonly authModel: Model<Auth>,
@InjectModel('auth_session')
private readonly authSessionModel: Model<AuthSession>,
private readonly jwtService: JwtService,
) {}
async canActivate(context: ExecutionContext) {
Expand All @@ -34,10 +35,13 @@ export class AuthGuard implements CanActivate {
secret: process.env.JWT_SECRET,
});

const userAuth = await this.authModel.findOne({
sessions: decoded.sessionId,
const userAuth = await this.authSessionModel.findOne({
sessionId: decoded.sessionId,
});
if (!userAuth) throw new Error();

if (!userAuth) {
throw new Error();
}

const guildId = request.headers['x-guild-id'] as string;
request.userData = { ...decoded, guildId };
Expand Down
19 changes: 19 additions & 0 deletions src/modules/auth/model/auth-session.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Types } from 'mongoose';

@Schema()
export class AuthSession {
@Prop({ ref: 'User' })
userId: Types.ObjectId;

@Prop()
discordAccessToken: string;

@Prop()
sessionId: string;

@Prop({ default: new Date(), index: { expireAfterSeconds: 604800 } })
createdAt: Date;
}

export const AuthSessionSchema = SchemaFactory.createForClass(AuthSession);
18 changes: 0 additions & 18 deletions src/modules/auth/model/auth.model.ts

This file was deleted.

20 changes: 8 additions & 12 deletions src/modules/auth/service/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { InjectModel } from '@nestjs/mongoose';
import 'dotenv/config';
import { Model, Types } from 'mongoose';
import { PROVIDER_TYPES } from 'src/core/provider.types';
import { Auth } from 'src/modules/auth/model/auth.model';
import { AuthSession } from 'src/modules/auth/model/auth-session.model';
import { DiscordAuthService } from 'src/modules/auth/service/discord_auth.service';
import { UserRepository } from 'src/modules/users/repository/user.repo';
import { UserService } from 'src/modules/users/service/user.service';
Expand All @@ -21,7 +21,8 @@ export class AuthService {
@Inject(UserRepository) private readonly userRepository: UserRepository,
private readonly jwtService: JwtService,
@Inject(UserService) private readonly userService: UserService,
@InjectModel(Auth.name) private readonly authModel: Model<Auth>,
@InjectModel('auth_session')
private readonly authSessionModel: Model<AuthSession>,
) {}

async discordLogin(code: string) {
Expand All @@ -47,7 +48,6 @@ export class AuthService {
});

localUserId = createdUser.id;
await this.authModel.insertMany({ userId: createdUser._id });
} else {
/**Update local user profile */
await this.userRepository.update(new Types.ObjectId(localUserId), {
Expand All @@ -72,15 +72,11 @@ export class AuthService {
{ expiresIn: '7d' },
);

await this.authModel.updateOne(
{ userId: new Types.ObjectId(localUserId) },
{
discordAccessToken: getToken.access_token,
$push: {
sessions: sessionId,
},
},
);
await this.authSessionModel.insertMany({
userId: new Types.ObjectId(localUserId),
discordAccessToken: getToken.access_token,
sessionId,
});

return {
accessToken: jwt,
Expand Down

0 comments on commit d5f1ee4

Please sign in to comment.