Skip to content

Commit

Permalink
fix(#404): Getting the Client's Ip Adress using request_ip package
Browse files Browse the repository at this point in the history
  • Loading branch information
JacquelineTuyisenge committed Oct 28, 2024
1 parent 51b182a commit 0c221d0
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 15 deletions.
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
"node-fetch": "^2.6.12",
"nodemailer": "^6.7.8",
"normalize-mongoose": "^1.0.0",
"request-ip": "^3.3.0",
"ts-node-dev": "^2.0.0",
"tslog": "^4.9.2",
"ws": "^8.11.0",
Expand All @@ -99,6 +100,7 @@
"@types/node": "^13.13.52",
"@types/node-fetch": "^2.6.4",
"@types/nodemailer": "^6.4.6",
"@types/request-ip": "^0.0.41",
"@types/ws": "^8.5.10",
"@types/xlsx": "^0.0.35",
"@typescript-eslint/eslint-plugin": "^4.0.1",
Expand Down
8 changes: 7 additions & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { GraphQLError } from 'graphql'
import 'dotenv/config'
import { Request } from 'express'
import * as jwt from 'jsonwebtoken'
import requestIp from 'request-ip'

const SECRET = process.env.SECRET || 'test_secret'

Expand Down Expand Up @@ -34,23 +35,28 @@ export function decodeAuthHeader(authHeader: string): AuthTokenPayload {
export interface Context {
userId?: string
role?: string
clientIpAdress?: string
}

export const context = async ({ req }: { req: Request }): Promise<Context> => {
const token =
req && req.headers.authorization
? decodeAuthHeader(req.headers.authorization)
: null

//get Ip
const clientIpAdress = requestIp.getClientIp(req) || undefined
if (
!token &&
!req.body.variables.organisationInput &&
!req.body.variables.loginInput
) {
return {}
return { clientIpAdress }
} else {
return {
userId: token?.userId,
role: token?.role,
clientIpAdress,
}
}
}
29 changes: 15 additions & 14 deletions src/resolvers/userResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,21 @@ enum Status {
rejected = 'rejected',
}

async function logGeoActivity(user: any) {
const ipResponse = await fetch('https://api.ipify.org?format=json')
const { ip: realIp } = await ipResponse.json()
async function logGeoActivity(user: any, clientIpAdress: string) {
const response = await fetch(`https://ipapi.co/${clientIpAdress}/json/`)

const response = await fetch(`https://ipapi.co/${realIp}/json/`)
const geoData = await response.json()

const profile = await Profile.findOne({ user: user._id })
if (!profile) {
throw new Error('Profile not found for the user')
return
}

if (geoData.country_code && geoData.city) {
profile.activity.push({
country_code: geoData.country_code,
country_name: geoData.country_name,
IPv4: realIp,
IPv4: clientIpAdress,
city: geoData.city,
state: geoData.region,
postal: geoData.postal,
Expand All @@ -73,7 +71,7 @@ async function logGeoActivity(user: any) {
})
await profile.save()
} else {
console.log('skipping activity due to incomplete geo data')
console.log('No data found in Geo API')
profile.activity.push({
failed: 1,
date: new Date().toISOString(),
Expand Down Expand Up @@ -334,8 +332,11 @@ const resolvers: any = {

async loginUser(
_: any,
{ loginInput: { email, password, orgToken } }: any
{ loginInput: { email, password, orgToken } }: any,
context: any
) {
const { clientIpAdress } = context

// get the organization if someone logs in
const org: InstanceType<typeof Organization> =
await checkLoggedInOrganization(orgToken)
Expand Down Expand Up @@ -392,7 +393,7 @@ const resolvers: any = {
if (await isAssigned(org?.name, user._id)) {
const token = generateToken(user._id, user._doc?.role || 'user')

const geoData = await logGeoActivity(user)
const geoData = await logGeoActivity(user, clientIpAdress)

const data = {
token: token,
Expand All @@ -412,7 +413,7 @@ const resolvers: any = {
if (user.cohort && user.team) {
const token = generateToken(user._id, user._doc?.role || 'user')

const geoData = await logGeoActivity(user)
const geoData = await logGeoActivity(user, clientIpAdress)

const data = {
token: token,
Expand All @@ -433,7 +434,7 @@ const resolvers: any = {
if (user?.organizations?.includes(org?.name)) {
const token = generateToken(user._id, user._doc?.role || 'user')

const geoData = await logGeoActivity(user)
const geoData = await logGeoActivity(user, clientIpAdress)

const data = {
token: token,
Expand Down Expand Up @@ -465,7 +466,7 @@ const resolvers: any = {
user._doc?.role || 'user'
)

const geoData = await logGeoActivity(user)
const geoData = await logGeoActivity(user, clientIpAdress)

const managerData = {
token: managerToken,
Expand Down Expand Up @@ -503,7 +504,7 @@ const resolvers: any = {
user._doc?.role || 'user'
)

const geoData = await logGeoActivity(user)
const geoData = await logGeoActivity(user, clientIpAdress)

const coordinatorData = {
token: coordinatorToken,
Expand All @@ -520,7 +521,7 @@ const resolvers: any = {
user._doc?.role || 'user'
)

const geoData = await logGeoActivity(user)
const geoData = await logGeoActivity(user, clientIpAdress)

const superAdminData = {
token: superAdminToken,
Expand Down

0 comments on commit 0c221d0

Please sign in to comment.