Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ordercloud auth #936

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions packages/ordercloud/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@
},
"dependencies": {
"@vercel/commerce": "workspace:*",
"lodash.debounce": "^4.0.8",
"cookie": "^0.4.1"
"cookie": "^0.4.1",
"jsonwebtoken": "8.5.1",
"lodash.debounce": "^4.0.8"
},
"peerDependencies": {
"next": "^13",
Expand All @@ -60,11 +61,12 @@
"@taskr/clear": "^1.1.0",
"@taskr/esnext": "^1.1.0",
"@taskr/watch": "^1.1.0",
"@types/cookie": "^0.4.1",
"@types/jsonwebtoken": "8.5.7",
"@types/lodash.debounce": "^4.0.6",
"@types/node": "^17.0.8",
"@types/react": "^18.0.14",
"@types/cookie": "^0.4.1",
"@types/node-fetch": "^2.6.2",
"@types/react": "^18.0.14",
"lint-staged": "^12.1.7",
"next": "^13.0.6",
"prettier": "^2.5.1",
Expand Down
34 changes: 34 additions & 0 deletions packages/ordercloud/src/api/endpoints/customer/customer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { CustomerEndpoint } from '.'
import { CommerceAPIError } from '@vercel/commerce/api/utils/errors'

const getLoggedInCustomer: CustomerEndpoint['handlers']['getLoggedInCustomer'] =
async ({ req, config: { restBuyerFetch, tokenCookie } }) => {
const token = req.cookies.get(tokenCookie)?.value

if (token) {
const customer = await restBuyerFetch('GET', '/me', undefined, {
token,
})

if (!customer) {
throw new CommerceAPIError('Customer not found', {
status: 404,
})
}

return {
data: {
customer: {
id: customer.ID,
firstName: customer.FirstName,
lastName: customer.LastName,
email: customer.Email,
},
},
}
}

return { data: null }
}

export default getLoggedInCustomer
18 changes: 18 additions & 0 deletions packages/ordercloud/src/api/endpoints/customer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { GetAPISchema, createEndpoint } from '@vercel/commerce/api'
import customerEndpoint from '@vercel/commerce/api/endpoints/customer'
import type { CustomerSchema } from '@vercel/commerce/types/customer'
import type { OrdercloudAPI } from '../..'
import getLoggedInCustomer from './customer'

export type CustomerAPI = GetAPISchema<OrdercloudAPI, CustomerSchema>

export type CustomerEndpoint = CustomerAPI['endpoint']

export const handlers: CustomerEndpoint['handlers'] = { getLoggedInCustomer }

const customerApi = createEndpoint<CustomerAPI>({
handler: customerEndpoint,
handlers,
})

export default customerApi
8 changes: 8 additions & 0 deletions packages/ordercloud/src/api/endpoints/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,21 @@ import createEndpoints from '@vercel/commerce/api/endpoints'

import cart from './cart'
import checkout from './checkout'
import login from './login'
import logout from './logout'
import signup from './signup'
import products from './catalog/products'
import customer from './customer'
import customerCard from './customer/card'
import customerAddress from './customer/address'

const endpoints = {
cart,
checkout,
login,
logout,
signup,
customer,
'customer/card': customerCard,
'customer/address': customerAddress,
'catalog/products': products,
Expand Down
18 changes: 18 additions & 0 deletions packages/ordercloud/src/api/endpoints/login/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { GetAPISchema, createEndpoint } from '@vercel/commerce/api'
import loginEndpoint from '@vercel/commerce/api/endpoints/login'
import type { LoginSchema } from '@vercel/commerce/types/login'
import type { OrdercloudAPI } from '../..'
import login from './login'

export type LoginAPI = GetAPISchema<OrdercloudAPI, LoginSchema>

export type LoginEndpoint = LoginAPI['endpoint']

export const handlers: LoginEndpoint['handlers'] = { login }

const loginApi = createEndpoint<LoginAPI>({
handler: loginEndpoint,
handlers,
})

export default loginApi
54 changes: 54 additions & 0 deletions packages/ordercloud/src/api/endpoints/login/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { LoginEndpoint } from '.'

import { FetcherError } from '@vercel/commerce/utils/errors'
import { CommerceAPIError } from '@vercel/commerce/api/utils/errors'
import { getFetchConfig, getToken } from '../..//utils/fetch-rest'
import { serialize } from 'cookie'

const invalidCredentials = /Invalid username or password/i

const login: LoginEndpoint['handlers']['login'] = async ({
body: { email, password },
config,
}) => {
try {
const token = await getToken({
grantType: 'password',
username: email,
password: password,
...getFetchConfig(config),
})

if (!token.access_token) {
throw new CommerceAPIError('Failed to retrieve access token', {
status: 401,
})
}

return {
headers: {
'Set-Cookie': serialize(config.tokenCookie, token.access_token, {
expires: new Date(Date.now() + token.expires_in * 1000),
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
}),
},
data: null,
}
} catch (error) {
// Check if the email and password didn't match an existing account
if (error instanceof FetcherError) {
throw new CommerceAPIError(
error.errors.some((e) => invalidCredentials.test(e.message))
? 'Cannot find an account that matches the provided credentials'
: error.message,
{ status: error.status || 401 }
)
} else {
throw error
}
}
}

export default login
18 changes: 18 additions & 0 deletions packages/ordercloud/src/api/endpoints/logout/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { GetAPISchema, createEndpoint } from '@vercel/commerce/api'
import logoutEndpoint from '@vercel/commerce/api/endpoints/logout'
import type { LogoutSchema } from '@vercel/commerce/types/logout'
import type { OrdercloudAPI } from '../..'
import logout from './logout'

export type LogoutAPI = GetAPISchema<OrdercloudAPI, LogoutSchema>

export type LogoutEndpoint = LogoutAPI['endpoint']

export const handlers: LogoutEndpoint['handlers'] = { logout }

const logoutApi = createEndpoint<LogoutAPI>({
handler: logoutEndpoint,
handlers,
})

export default logoutApi
25 changes: 25 additions & 0 deletions packages/ordercloud/src/api/endpoints/logout/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { serialize } from 'cookie'
import type { LogoutEndpoint } from '.'

const logout: LogoutEndpoint['handlers']['logout'] = async ({
body: { redirectTo },
config,
}) => {
const headers = {
'Set-Cookie': serialize(config.tokenCookie, '', {
maxAge: -1,
path: '/',
}),
}

return redirectTo
? {
redirectTo,
headers,
}
: {
headers,
}
}

export default logout
18 changes: 18 additions & 0 deletions packages/ordercloud/src/api/endpoints/signup/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { GetAPISchema, createEndpoint } from '@vercel/commerce/api'
import signupEndpoint from '@vercel/commerce/api/endpoints/signup'
import type { SignupSchema } from '@vercel/commerce/types/signup'
import type { OrdercloudAPI } from '../..'
import signup from './signup'

export type SignupAPI = GetAPISchema<OrdercloudAPI, SignupSchema>

export type SignupEndpoint = SignupAPI['endpoint']

export const handlers: SignupEndpoint['handlers'] = { signup }

const singupApi = createEndpoint<SignupAPI>({
handler: signupEndpoint,
handlers,
})

export default singupApi
60 changes: 60 additions & 0 deletions packages/ordercloud/src/api/endpoints/signup/signup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import type { SignupEndpoint } from '.'

import { decode, type JwtPayload } from 'jsonwebtoken'
import { serialize } from 'cookie'
import { CommerceAPIError } from '@vercel/commerce/api/utils/errors'

const signup: SignupEndpoint['handlers']['signup'] = async ({
req,
body: { firstName, lastName, password, email },
config: { restBuyerFetch, tokenCookie },
}) => {
// Get token
const token = req.cookies.get(tokenCookie)?.value

const accessToken = await restBuyerFetch(
'PUT',
`/me/register`,
{
Username: email,
Password: password,
FirstName: firstName,
LastName: lastName,
Email: email,
Active: true,
},
{
token,
anonToken: true,
}
).then((response: any) => {
return response.access_token
})

if (!accessToken) {
throw new CommerceAPIError('Failed to retrieve access token', {
status: 401,
})
}

const decodedToken = decode(accessToken) as JwtPayload
if (!decodedToken || !decodedToken.exp) {
throw new CommerceAPIError('Failed to decode access token', {
status: 500,
})
}

return {
headers: {
'Set-Cookie': serialize(tokenCookie, accessToken, {
expires: new Date(decodedToken.exp * 1000),
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
}),
},
data: null,
}
}

export default signup
Loading