Skip to content

Commit

Permalink
remove dulpicate codes by using code helper #326 (#339)
Browse files Browse the repository at this point in the history
  • Loading branch information
Bananayosostene authored Oct 7, 2024
1 parent 2fd15ac commit 4142322
Show file tree
Hide file tree
Showing 26 changed files with 340 additions and 352 deletions.
20 changes: 18 additions & 2 deletions src/helpers/user.helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
import { GraphQLError } from 'graphql'
import { User } from '../models/user'
import { RoleOfUser, User } from '../models/user'
import { Context } from './../context'
import * as jwt from 'jsonwebtoken'


const SECRET: string = process.env.SECRET ?? 'test_secret'

export const generateToken = (userId: string, role: string) => {
return jwt.sign({ userId, role }, SECRET, { expiresIn: '2h' })
}
export const generateTokenUserExists = (email: string) => {
return jwt.sign({ email }, SECRET, { expiresIn: '2d' })
}
export const generateTokenOrganization = (name: string) => {
return jwt.sign({ name }, SECRET, { expiresIn: '336h' })
}

export const emailExpression = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

export async function checkUserLoggedIn(
context: Context
Expand All @@ -24,7 +40,7 @@ export async function checkUserLoggedIn(
})
}

return (inputRoles: Array<string> = ['admin']) => {
return (inputRoles: Array<string> = [RoleOfUser.ADMIN]) => {
if (inputRoles && !inputRoles.includes(role as string)) {
throw new GraphQLError(
`Request ${inputRoles.join(' or ')} permission!!`,
Expand Down
9 changes: 5 additions & 4 deletions src/models/invitation.model.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mongoose, { Schema } from 'mongoose'
import { RoleOfUser } from './user'

const STATUS = {
PENDING: 'pending',
Expand All @@ -8,10 +9,10 @@ const STATUS = {
}

const ROLE = {
TRAINEE: 'trainee',
ADMIN: 'admin',
TTL: 'ttl',
COORDINATOR: 'coordinator',
TRAINEE: RoleOfUser.TRAINEE,
ADMIN: RoleOfUser.ADMIN,
TTL: RoleOfUser.TTL,
COORDINATOR: RoleOfUser.COORDINATOR,
}
const InvitationSchema = new Schema({
inviterId: {
Expand Down
8 changes: 8 additions & 0 deletions src/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ export interface UserInterface {
emailNotifications: boolean;
}

export enum RoleOfUser {
TRAINEE = 'trainee',
COORDINATOR = 'coordinator',
MANAGER = 'manager',
ADMIN = 'admin',
SUPER_ADMIN = 'superAdmin',
TTL = 'ttl',
}
mongoose.set('toJSON', {
virtuals: true,
versionKey: false,
Expand Down
14 changes: 7 additions & 7 deletions src/resolvers/attendance.resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import mongoose, { Error, Types } from 'mongoose'
import { checkUserLoggedIn } from '../helpers/user.helpers'
import { pushNotification } from '../utils/notification/pushNotification'
import Phase from '../models/phase.model'
import { User, UserInterface } from '../models/user'
import { RoleOfUser, User, UserInterface } from '../models/user'
import Team from '../models/team.model'
import { CohortInterface } from '../models/cohort.model'
import { GraphQLError } from 'graphql'
Expand Down Expand Up @@ -111,7 +111,7 @@ const attendanceResolver = {
{ traineeEmail }: any,
context: Context
) {
;(await checkUserLoggedIn(context))(['trainee'])
;(await checkUserLoggedIn(context))([RoleOfUser.TRAINEE])
const attendance = await Attendance.find()

const weeklyAttendance = attendance.map((week: any) => {
Expand All @@ -130,8 +130,8 @@ const attendanceResolver = {
{ team }: { team: string },
context: Context
) {
;(await checkUserLoggedIn(context))(['coordinator'])
const { userId } = (await checkUserLoggedIn(context))(['coordinator'])
;(await checkUserLoggedIn(context))([RoleOfUser.COORDINATOR])
const { userId } = (await checkUserLoggedIn(context))([RoleOfUser.COORDINATOR])

const teamData = await Team.findById(team)

Expand All @@ -143,8 +143,8 @@ const attendanceResolver = {
},

async getAttendanceStats(_: any, args: any, context: Context) {
;(await checkUserLoggedIn(context))(['coordinator'])
const { userId } = (await checkUserLoggedIn(context))(['coordinator'])
;(await checkUserLoggedIn(context))([RoleOfUser.COORDINATOR])
const { userId } = (await checkUserLoggedIn(context))([RoleOfUser.COORDINATOR])
const attendances: any = await Attendance.find({ coordinatorId: userId })

//calculate statistic
Expand Down Expand Up @@ -490,4 +490,4 @@ const attendanceResolver = {
},
}

export default attendanceResolver
export default attendanceResolver
44 changes: 22 additions & 22 deletions src/resolvers/cohort.resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { checkUserLoggedIn } from '../helpers/user.helpers'
import Cohort from '../models/cohort.model'
import Program from '../models/program.model'
import Phase from '../models/phase.model'
import { User } from '../models/user'
import { RoleOfUser, User } from '../models/user'
import { Organization } from '../models/organization.model'
import { Context } from './../context'
import { ProgramType } from './program.resolvers'
Expand All @@ -32,14 +32,14 @@ const resolvers = {
try {
// some validations
const { userId, role }: any = (await checkUserLoggedIn(context))([
'superAdmin',
'admin',
'manager',
RoleOfUser.SUPER_ADMIN,
RoleOfUser.ADMIN,
RoleOfUser.MANAGER,
])

// get the organization if a superAdmin logs in
let org
if (role !== 'superAdmin') {
if (role !== RoleOfUser.SUPER_ADMIN) {
org = await checkLoggedInOrganization(orgToken)
}

Expand All @@ -49,12 +49,12 @@ const resolvers = {
return (
await Cohort.find().populate({
path: 'program',
match: role === 'manager' && managerMatch,
match: role === RoleOfUser.MANAGER && managerMatch,
model: Program,
strictPopulate: false,
populate: {
path: 'organization',
match: role === 'admin' && adminMatch,
match: role === RoleOfUser.ADMIN && adminMatch,
model: Organization,
strictPopulate: false,
},
Expand Down Expand Up @@ -101,7 +101,7 @@ const resolvers = {
} = args

// some validations
;(await checkUserLoggedIn(context))(['superAdmin', 'admin', 'manager'])
;(await checkUserLoggedIn(context))([RoleOfUser.SUPER_ADMIN, RoleOfUser.ADMIN, RoleOfUser.MANAGER])
const coordinator = await User.findOne({
email: coordinatorEmail,
})
Expand Down Expand Up @@ -213,10 +213,10 @@ const resolvers = {
} = args

const { userId, role }: any = (await checkUserLoggedIn(context))([
'superAdmin',
'admin',
'manager',
'coordinator',
RoleOfUser.SUPER_ADMIN,
RoleOfUser.ADMIN,
RoleOfUser.MANAGER,
RoleOfUser.COORDINATOR,
])
const coordinator = await User.findOne({
email: coordinatorEmail,
Expand Down Expand Up @@ -294,7 +294,7 @@ const resolvers = {
})
}

if (role !== 'superAdmin') {
if (role !== RoleOfUser.SUPER_ADMIN) {
const org = await checkLoggedInOrganization(orgToken)

if (cohortOrg.id.toString() !== org.id.toString()) {
Expand All @@ -307,7 +307,7 @@ const resolvers = {
}
)
}
if (role === 'admin' && !cohortOrg?.admin?.includes(userId)) {
if (role === RoleOfUser.ADMIN && !cohortOrg?.admin?.includes(userId)) {
throw new GraphQLError(
`Cohort with id "${id}" doesn't exist in your organization`,
{
Expand All @@ -318,7 +318,7 @@ const resolvers = {
)
}
if (
role === 'manager' &&
role === RoleOfUser.MANAGER &&
cohortProgram?.manager?.toString() !== userId?.toString()
) {
throw new GraphQLError(
Expand All @@ -331,7 +331,7 @@ const resolvers = {
)
}
if (
role === 'coordinator' &&
role === RoleOfUser.COORDINATOR &&
cohort?.coordinator?.toString() !== userId?.toString()
) {
throw new GraphQLError('You are not assigned this cohort!', {
Expand Down Expand Up @@ -410,9 +410,9 @@ const resolvers = {
},
deleteCohort: async (_: any, { id, orgToken }: any, context: Context) => {
const { userId, role } = (await checkUserLoggedIn(context))([
'superAdmin',
'admin',
'manager',
RoleOfUser.SUPER_ADMIN,
RoleOfUser.ADMIN,
RoleOfUser.MANAGER,
])

const cohort = await Cohort.findById(id).populate({
Expand All @@ -433,7 +433,7 @@ const resolvers = {
const cohortProgram = cohort.program as ProgramType
const cohortOrg = cohortProgram.organization as OrganizationType

if (role !== 'superAdmin') {
if (role !== RoleOfUser.SUPER_ADMIN) {
const org = await checkLoggedInOrganization(orgToken)

if (cohortOrg.id.toString() !== org.id.toString()) {
Expand All @@ -447,7 +447,7 @@ const resolvers = {
)
}
if (
role === 'admin' &&
role === RoleOfUser.ADMIN &&
cohortOrg.admin.toString() !== userId?.toString()
) {
throw new GraphQLError(
Expand All @@ -460,7 +460,7 @@ const resolvers = {
)
}
if (
role === 'manager' &&
role === RoleOfUser.MANAGER &&
cohortProgram?.manager?.toString() !== userId?.toString()
) {
throw new GraphQLError(
Expand Down
Loading

0 comments on commit 4142322

Please sign in to comment.