Skip to content

Commit

Permalink
Merge pull request #13 from nation3/refactor-implement-basic-auth-com…
Browse files Browse the repository at this point in the history
…patible-with-vercel-(#2)

refactor: implement basic auth compatible with vercel (#2)
  • Loading branch information
aahna-ashina authored May 28, 2022
2 parents 39002bd + 25a43a1 commit c584023
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 97 deletions.
14 changes: 0 additions & 14 deletions server/package-lock.json

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

1 change: 0 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"google-auth-library": "^8.0.2",
"jsonwebtoken": "^8.5.1",
"next": "^12.1.6",
"nextjs-basic-auth": "^0.1.3",
"wagmi": "^0.3.5"
},
"devDependencies": {
Expand Down
48 changes: 48 additions & 0 deletions server/pages/api/_middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { NextFetchEvent, NextRequest } from 'next/server'

export function middleware(req: NextRequest, event: NextFetchEvent) {
console.log('middleware')

const pathName = req.nextUrl.pathname
console.log('pathName:', pathName)

// Perform Basic Auth on these paths:
// /api/pushNotification
// /api/pushUpdate
if (pathName.startsWith('/api/push')) {
const authorizationHeader = req.headers.get('authorization')
console.log('authorizationHeader:', authorizationHeader)

let wrongCredentials : boolean = false
if (authorizationHeader) {
// Get header value from "Basic <value>"
const headerValueBase64 = authorizationHeader.split(' ')[1]

// Decode from Base64
const headerValue = Buffer.from(headerValueBase64, 'base64').toString()

// Extract values from "<username>:<password>"
const [username, password] = headerValue.split(':')

// Get environment variables
const basicAuthUsername = String(process.env.BASIC_AUTH_USERNAME)
const basicAuthPassword = String(process.env.BASIC_AUTH_PASSWORD)

// Compare credentials
if ((username !== basicAuthUsername) || (password !== basicAuthPassword)) {
wrongCredentials = true
}
}
console.log('wrongCredentials:', wrongCredentials)

if (!authorizationHeader || wrongCredentials) {
// Perform Basic Auth
return new Response('401 Unauthorized', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Secure Area"',
},
})
}
}
}
77 changes: 30 additions & 47 deletions server/pages/api/pushNotification.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,38 @@
import { NextApiRequest, NextApiResponse } from "next"
import basicAuthCheck from "../../utils/basicAuthCheck"
import { Passes } from "../../utils/Passes"

async function performBasicAuth(req: NextApiRequest, res: NextApiResponse) {
console.log('performBasicAuth')
await basicAuthCheck(req, res)
return res
}

// req = HTTP incoming message, res = HTTP server response
export default function handler(req: NextApiRequest, res: NextApiResponse) {
console.log('/api/pushNotification')

performBasicAuth(req, res)
.then(response => {
console.log('then')
console.log('response.statusCode', response.statusCode)
if (response.statusCode != 200) {
console.error(`Basic Auth failed: ${response.statusCode} ${response.statusMessage}`)
res.status(response.statusCode).json({ statusCode: response.statusCode, message: response.statusMessage })
} else {
// Push notification to all the passes
console.log('Pushing notification...')

const { title } = req.query
console.log(`title: "${title}"`)
if (!title || (String(title).trim().length == 0)) {
res.status(400).json({ error: 'Missing/empty parameter: title' })
return
}

const { content } = req.query
console.log(`content: "${content}"`)
if (!content || (String(content).trim().length == 0)) {
res.status(400).json({ error: 'Missing/empty parameter: content' })
return
}

// Remove leading/trailing whitespace
const trimmedTitle = String(title).trim()
const trimmedContent = String(content).trim()

// Push notification
const notificationSent: boolean = Passes.pushNotification(trimmedTitle, trimmedContent);
console.log('notificationSent:', notificationSent)

res.status(response.statusCode).json({
notificationSent: notificationSent,
title: trimmedTitle,
content: trimmedContent
})
}
})
// Push notification to all the passes
console.log('Pushing notification...')

const { title } = req.query
console.log(`title: "${title}"`)
if (!title || (String(title).trim().length == 0)) {
res.status(400).json({ error: 'Missing/empty parameter: title' })
return
}

const { content } = req.query
console.log(`content: "${content}"`)
if (!content || (String(content).trim().length == 0)) {
res.status(400).json({ error: 'Missing/empty parameter: content' })
return
}

// Remove leading/trailing whitespace
const trimmedTitle = String(title).trim()
const trimmedContent = String(content).trim()

// Push notification
const notificationSent: boolean = Passes.pushNotification(trimmedTitle, trimmedContent);
console.log('notificationSent:', notificationSent)

res.status(200).json({
notificationSent: notificationSent,
title: trimmedTitle,
content: trimmedContent
})
}
29 changes: 6 additions & 23 deletions server/pages/api/pushUpdate.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,15 @@
import { NextApiRequest, NextApiResponse } from "next"
import basicAuthCheck from "../../utils/basicAuthCheck"
import { Passes } from "../../utils/Passes"

async function performBasicAuth(req: NextApiRequest, res: NextApiResponse) {
console.log('performBasicAuth')
await basicAuthCheck(req, res)
return res
}

// req = HTTP incoming message, res = HTTP server response
export default function handler(req: NextApiRequest, res: NextApiResponse) {
console.log('/api/pushUpdate')

performBasicAuth(req, res)
.then(response => {
console.log('then')
console.log('response.statusCode', response.statusCode)
if (response.statusCode != 200) {
console.error(`Basic Auth failed: ${response.statusCode} ${response.statusMessage}`)
res.status(response.statusCode).json({ statusCode: response.statusCode, message: response.statusMessage })
} else {
// Push update of new template
console.log('Pushing template update...')

const templateFormatVersion: number = 1
const updateSent: boolean = Passes.pushUpdate(templateFormatVersion)
// Push update of new template
console.log('Pushing template update...')

const templateFormatVersion: number = 1
const updateSent: boolean = Passes.pushUpdate(templateFormatVersion)

res.status(response.statusCode).json({ updateSent: updateSent, templateFormatVersion: templateFormatVersion })
}
})
res.status(200).json({updateSent: updateSent, templateFormatVersion: templateFormatVersion })
}
12 changes: 0 additions & 12 deletions server/utils/basicAuthCheck.ts

This file was deleted.

1 comment on commit c584023

@vercel
Copy link

@vercel vercel bot commented on c584023 May 28, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

mobile-passport – ./

mobile-passport-nation3.vercel.app
mobile-passport.vercel.app
mobile-passport-git-main-nation3.vercel.app

Please sign in to comment.