Skip to content

Commit

Permalink
Combine methods + update packages
Browse files Browse the repository at this point in the history
  • Loading branch information
sam-lippert committed Sep 28, 2023
1 parent 851ce52 commit c32b041
Show file tree
Hide file tree
Showing 4 changed files with 1,257 additions and 5,697 deletions.
27 changes: 11 additions & 16 deletions pkg/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,10 @@ export class API {

if (!env.CTX) console.warn('[CTX] env.CTX is undefined, using fetch to ctx.do.')

const contextVin = env.CTX != undefined ? await env.CTX.fetch(req).then(x=>x.json()) : await fetch(authReq).then(res => res.json())
const context = env.CTX != undefined ? await env.CTX.fetch(req).then(x=>x.json()) : await fetch(authReq).then(res => res.json())

req.user = contextVin.user
req.ctx = contextVin
req.user = context.user
req.ctx = context
req.env = env

const user = req.user
Expand All @@ -133,16 +133,8 @@ export class API {
req.metadata = this.metadata

if (this?.options?.requireAuth) {
if (!user?.authenticated) {
return json({
api: this.metadata,
data: {
error: 'You must be logged in to access this API.',
link: `https://${hostname}/login`
},
user,
})
}
const redirect = loginRedirect(hostname, user, this.metadata)
if (redirect) return redirect
}

if (pathname == '/api') {
Expand Down Expand Up @@ -257,15 +249,18 @@ export const json=(e,t)=>new Response(JSON.stringify(e,null,2),{headers:{"conten
export const requiresAuth = async (req) => {
// Middleware version of our auth system
const { hostname } = new URL(req.url)
return loginRedirect(hostname, req.user, req.metadata)
}

if (!req.user.authenticated) {
function loginRedirect(hostname, user, metadata) {
if (!user?.authenticated) {
return json({
api: req.metadata,
api: metadata,
data: {
error: 'You must be logged in to access this API.',
link: `https://${hostname}/login`
},
user: req.user,
user,
}, {
status: 403
})
Expand Down
Loading

2 comments on commit c32b041

@workers-do
Copy link

Choose a reason for hiding this comment

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

@vercel
Copy link

@vercel vercel bot commented on c32b041 Sep 28, 2023

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:

apis-do – ./

apis-do.dev.driv.ly
apis-do-git-main.dev.driv.ly
apis.do

Please sign in to comment.