Added autoLogin

This commit is contained in:
Douglas Barone 2023-10-26 07:10:45 -04:00
parent 69d5002cfd
commit d28ca3fce2
5 changed files with 47 additions and 20 deletions

View File

@ -0,0 +1,12 @@
import { PaFirewallService } from '../services/PaFirewallService'
import { db } from '../prisma'
export async function autoLogin(username: string, domain: string, ip: string) {
console.log('AutoLogin?', username, domain, ip)
const paHosts = await db.paHost.findMany()
const pa = new PaFirewallService(paHosts[0].ip, paHosts[0].key)
return await pa.login(username, ip, domain)
}

View File

@ -1,6 +0,0 @@
export type NetworkInfo = {
ip: string
source: 'IP' | 'X-Forwarded-For'
status: 'Mapped' | 'Expired' | 'ERROR' | 'Prohibited' | 'Unknown'
// campus: 'PP' | 'DR' | 'RT' | 'JD'
}

View File

@ -1,38 +1,59 @@
import { initTRPC, inferAsyncReturnType } from '@trpc/server'
import { initTRPC, inferAsyncReturnType, TRPCError } from '@trpc/server'
import * as trpcExpress from '@trpc/server/adapters/express'
import { z } from 'zod'
import { login } from './lib/login'
import { getIpFromRequest } from './lib/getIpFromContext'
import { getIpFromRequest } from './lib/getIpFromRequest'
import { logout } from './lib/logout'
import { PaFirewallService } from './services/PaFirewallService'
import { jwtService } from './lib/jwt'
import { autoLogin } from './lib/autoLogin'
// Created for each request
function createContext({ req, res }: trpcExpress.CreateExpressContextOptions) {
const ip = getIpFromRequest(req)
return { ip }
const token = req.headers.authorization?.split(' ')[1]
const jwtPayload = token ? jwtService.verifyToken(token) : null
return { ip, user: jwtPayload }
}
export type Context = inferAsyncReturnType<typeof createContext>
export const t = initTRPC.context<Context>().create()
const { query, mutation, input } = t.procedure
export const appRouter = t.router({
myIp: t.procedure.query(({ ctx }) => {
myIp: query(({ ctx }) => {
if (!ctx.ip) throw new Error('Erro ao obter endereço IP')
return ctx.ip
}),
login: t.procedure
.input(z.object({ username: z.string(), password: z.string() }))
.mutation(async ({ input, ctx }) => {
login: input(
z.object({ username: z.string(), password: z.string() })
).mutation(async ({ input, ctx }) => {
return await login(input.username, input.password, ctx.ip)
}),
logout: t.procedure
.input(z.object({ username: z.string(), domain: z.string() }))
.mutation(async ({ input, ctx }) => {
logout: input(
z.object({ username: z.string(), domain: z.string() })
).mutation(async ({ input, ctx }) => {
return await logout(input.username, input.domain, ctx.ip)
}),
autoLogin: mutation(async ({ ctx }) => {
if (!ctx.user)
throw new TRPCError({
message: 'Erro ao obter usuário',
code: 'UNAUTHORIZED'
})
const { username, domain } = ctx.user
return await autoLogin(username, ctx.ip, domain)
}),
addFirewall: t.procedure
.input(
z.object({

View File