Skip to content
This repository has been archived by the owner on Dec 13, 2024. It is now read-only.

Commit

Permalink
feat: adds auth data from other collections during user login
Browse files Browse the repository at this point in the history
  • Loading branch information
zakhaev26 committed Mar 15, 2024
1 parent 1715ae0 commit 3760b4a
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 25 deletions.
84 changes: 81 additions & 3 deletions apis/src/authentication.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,100 @@
import { ServiceAddons } from '@feathersjs/feathers';
import { HookContext, Paginated, Params, ServiceAddons } from '@feathersjs/feathers';
import { AuthenticationService, JWTStrategy } from '@feathersjs/authentication';
import { LocalStrategy } from '@feathersjs/authentication-local';
import { expressOauth } from '@feathersjs/authentication-oauth';

import { Application } from './declarations';
import { Users } from './services/users/users.class';
import RolesEnum from './constants/roles.enum';
import { Player } from './services/player/player.class';
import { PlatformSuperAdmin } from './services/platform-super-admin/platform-super-admin.class';
import { Admin } from './services/admin/admin.class';

declare module './declarations' {
interface ServiceTypes {
'authentication': AuthenticationService & ServiceAddons<any>;
}
}

export default function(app: Application): void {
export default function (app: Application): void {
const authentication = new AuthenticationService(app);

class CustomLocalStrategy extends LocalStrategy {
async findEntity(username: string, params: Params): Promise<any> {
// Find the user entity
console.log(`username = ${username}`)
const UserService: Users & ServiceAddons<any> = app.service('users');
const user: any[] | Paginated<any> = await UserService.find({
query: { email: username },
paginate: false // To get only one user
});
// @ts-ignore
if (user.length === 0) {
return null; // User not found
}

// Get the first user (assuming email is unique)
// @ts-ignore
const foundUser = user[0];
return { ...foundUser };
}
}

authentication.register('jwt', new JWTStrategy());
authentication.register('local', new LocalStrategy());
authentication.register('local', new CustomLocalStrategy());

app.use('/authentication', authentication);
app.configure(expressOauth());
const service = app.service('authentication');

service.hooks({
after: {
create: [
async (context: HookContext) => {
const { user } = context.result;
console.log(user);

if (user.role === RolesEnum.PLAYER) {
// Load player data
let playerData = null;
const playerService: Player & ServiceAddons<any> = app.service('player');
const player = await playerService._find({
query: { user: user._id },
paginate: false
});
playerData = player.length > 0 ? player[0] : null;

console.log(playerData)
context.result.user.playerData = playerData;
}

if (user.role === RolesEnum.ADMIN) {
let adminData = null;
const adminService: Admin & ServiceAddons<any> = app.service('admin');
const psa = await adminService._find({
query: { user: user._id },
paginate: false
});

adminData = psa.length > 0 ? psa[0] : null;
console.log(adminData)
context.result.user.adminData = adminData;
}

if (user.role === RolesEnum.PLATFORM_SUPER_ADMIN) {
let psaData = null;
const psaService: PlatformSuperAdmin & ServiceAddons<any> = app.service('platform-super-admin');
const psa = await psaService._find({
query: { user: user._id },
paginate: false
});
psaData = psa.length > 0 ? psa[0] : null;

console.log(psaData)
context.result.user.psaData = psaData;
}
}
]
}
});
}
21 changes: 21 additions & 0 deletions apis/src/hooks/block-cross-delete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
import { BadRequest } from '@feathersjs/errors';
import { Hook, HookContext } from '@feathersjs/feathers';
import RolesEnum from '../constants/roles.enum';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export default (options: object = {}): Hook => {
return async (context: HookContext): Promise<HookContext> => {


const targetId = context.id;
const { user } = context.params;
// @ts-ignore
if(user.role === RolesEnum.PLATFORM_SUPER_ADMIN) return context
// @ts-ignore
const initiatorId = user._id.toString();
if(initiatorId === targetId) return context;
throw new BadRequest('users cannot delete other users')
};
};
10 changes: 1 addition & 9 deletions apis/src/models/platform-super-admin.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,7 @@ export default function (app: Application): Model<any> {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
required: true,
},
contactNo: {
type: String
},
socials: [
{
type: Object
}
],
}
}, {
timestamps: true
});
Expand Down
3 changes: 2 additions & 1 deletion apis/src/models/player.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ export default function (app: Application): Model<any> {
ref: 'player'
},
deletedAt: {
type: Date
type: Date,
default:Date.now()
},
}, {
timestamps: true
Expand Down
4 changes: 3 additions & 1 deletion apis/src/services/player/player.hooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { HooksObject } from '@feathersjs/feathers';
import * as authentication from '@feathersjs/authentication';
import BlockCrossDelete from '../../hooks/block-cross-delete';
import { discard } from 'feathers-hooks-common';
// Don't remove this comment. It's needed to format import lines nicely.

const { authenticate } = authentication.hooks;
Expand All @@ -12,7 +14,7 @@ export default {
create: [],
update: [],
patch: [],
remove: []
remove: [BlockCrossDelete()]
},

after: {
Expand Down
3 changes: 2 additions & 1 deletion apis/src/services/users/users.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ export class Users extends Service {
const otp = generateOTP();
const secret = app.settings.authentication.secret;
data.role = RolesEnum.PLAYER;
console.log(data)
const token = jwt.sign({
player: data,
user: data,
otp
}, secret);

Expand Down
17 changes: 10 additions & 7 deletions apis/src/services/users/verification/verification.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { extractTokenFromHeader } from '../../../utils/extractTokenFromHeader';
import { BadRequest } from '@feathersjs/errors';
import { Service } from 'feathers-mongoose';
import { Users } from '../users.class';

import * as jwt from "jsonwebtoken"
interface Data { }

interface ServiceOptions { }
Expand Down Expand Up @@ -43,16 +43,19 @@ export class Verification implements ServiceMethods<Data> {
const secret = this.app.settings.authentication.secret;

// @ts-ignore
const { player, otp } = jwt.decode(token, secret);
console.log('player = ', player);
if (!player) throw new BadRequest('Invalid Token');

const decodedVal = jwt.decode(token, secret);
console.log(decodedVal)
// @ts-ignore
const { user, otp } = decodedVal
console.log('user = ', user);
if (!user) throw new BadRequest('Invalid Token');

// @ts-ignore
if (otp === data.otp) {
const UserService: Users & ServiceAddons<any> = this.app.service('users');
console.log(player);
const user = await UserService._create(player);
return user
console.log(user);
return await UserService._create(user);
}
else throw new Error('OTP is invalid');
} catch (error: any) {
Expand Down
9 changes: 6 additions & 3 deletions apis/src/services/users/verification/verification.hooks.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { HooksObject } from '@feathersjs/feathers';
import * as local from '@feathersjs/authentication-local';
import * as authentication from '@feathersjs/authentication';
// Don't remove this comment. It's needed to format import lines nicely.

const { authenticate } = authentication.hooks;

const { hashPassword, protect } = local.hooks;
export default {
before: {
all: [ authenticate('jwt') ],
all: [],
find: [],
get: [],
create: [],
Expand All @@ -16,7 +17,9 @@ export default {
},

after: {
all: [],
all: [
protect('password')
],
find: [],
get: [],
create: [],
Expand Down

0 comments on commit 3760b4a

Please sign in to comment.