Files
medusa-store/packages/medusa/src/services/auth.ts
T
2caff2efc7 feat(medusa): Authentication overhaul (#4064)
* implemented bearer auth

* changed naming strat

* changed session auth to not use jwt

* typo

* changed auth header prefix for admin api token auth

* fixed supporting functions to work with new session type

* removed database calls for bearer auth improving performance

* removed unused deps

* changed auth in tests

* added integration tests

* Accepted suggested change

Co-authored-by: Carlos R. L. Rodrigues <37986729+carlos-r-l-rodrigues@users.noreply.github.com>

* Typo

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>

* more typos

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>

* proper formatting

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>

* removed endregion

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>

* removed startregion

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>

* fixed admin JWT integration test

* added more fixes to integration tests

* Update OAS

* Create fluffy-donkeys-hope.md

* created API reference for new auth

* implemented getToken in medusa-js

* Apply suggestions from code review

Co-authored-by: Shahed Nasser <shahednasser@gmail.com>

* Apply suggestions from code review

Co-authored-by: Shahed Nasser <shahednasser@gmail.com>

* deleted files which should be autogenerated

* Update fluffy-donkeys-hope.md

* JSDoc update

Co-authored-by: Oli Juhl <59018053+olivermrbl@users.noreply.github.com>

* added missing route exports

* implemented runtime domain safety in jwt token manager

* fixed jwt manager

* lint get-token files

* Update fluffy-donkeys-hope.md

* Revert "deleted files which should be autogenerated"

This reverts commit cd5e86623b822e6a6ac37322b952143ccc493df9.

* Revert "Apply suggestions from code review"

This reverts commit f02f07ce58fd9fcc2dfc80cadbb9df2665108d65.

* Revert "created API reference for new auth"

This reverts commit c9eafbb36453f5cf8047c79e94f470cb2d023c7d.

* renamed header for sending api access tokens

* medusa-js - changed apiKey header

---------

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>
Co-authored-by: Carlos R. L. Rodrigues <37986729+carlos-r-l-rodrigues@users.noreply.github.com>
Co-authored-by: olivermrbl <oliver@mrbltech.com>
Co-authored-by: Shahed Nasser <shahednasser@gmail.com>
2023-09-25 13:57:44 -04:00

171 lines
4.9 KiB
TypeScript

import Scrypt from "scrypt-kdf"
import { AuthenticateResult } from "../types/auth"
import { Customer, User } from "../models"
import { TransactionBaseService } from "../interfaces"
import UserService from "./user"
import CustomerService from "./customer"
import { EntityManager } from "typeorm"
type InjectedDependencies = {
manager: EntityManager
userService: UserService
customerService: CustomerService
}
/**
* Can authenticate a user based on email password combination
*/
class AuthService extends TransactionBaseService {
protected readonly userService_: UserService
protected readonly customerService_: CustomerService
constructor({ userService, customerService }: InjectedDependencies) {
// eslint-disable-next-line prefer-rest-params
super(arguments[0])
this.userService_ = userService
this.customerService_ = customerService
}
/**
* Verifies if a password is valid given the provided password hash
* @param {string} password - the raw password to check
* @param {string} hash - the hash to compare against
* @return {bool} the result of the comparison
*/
protected async comparePassword_(
password: string,
hash: string
): Promise<boolean> {
const buf = Buffer.from(hash, "base64")
return Scrypt.verify(buf, password)
}
/**
* Authenticates a given user with an API token
* @param {string} token - the api_token of the user to authenticate
* @return {AuthenticateResult}
* success: whether authentication succeeded
* user: the user document if authentication succeeded
* error: a string with the error message
*/
async authenticateAPIToken(token: string): Promise<AuthenticateResult> {
return await this.atomicPhase_(async (transactionManager) => {
try {
const user: User = await this.userService_
.withTransaction(transactionManager)
.retrieveByApiToken(token)
return {
success: true,
user,
}
} catch (error) {
return {
success: false,
error: "Invalid API Token",
}
}
})
}
/**
* Authenticates a given user based on an email, password combination. Uses
* scrypt to match password with hashed value.
* @param {string} email - the email of the user
* @param {string} password - the password of the user
* @return {AuthenticateResult}
* success: whether authentication succeeded
* user: the user document if authentication succeeded
* error: a string with the error message
*/
async authenticate(
email: string,
password: string
): Promise<AuthenticateResult> {
return await this.atomicPhase_(async (transactionManager) => {
try {
const userPasswordHash: User = await this.userService_
.withTransaction(transactionManager)
.retrieveByEmail(email, {
select: ["password_hash"],
})
const passwordsMatch = await this.comparePassword_(
password,
userPasswordHash.password_hash
)
if (passwordsMatch) {
const user = await this.userService_
.withTransaction(transactionManager)
.retrieveByEmail(email)
return {
success: true,
user: user,
}
}
} catch (error) {
console.log("error ->", error)
// ignore
}
return {
success: false,
error: "Invalid email or password",
}
})
}
/**
* Authenticates a customer based on an email, password combination. Uses
* scrypt to match password with hashed value.
* @param {string} email - the email of the user
* @param {string} password - the password of the user
* @return {{ success: (bool), customer: (object | undefined) }}
* success: whether authentication succeeded
* customer: the customer document if authentication succeded
* error: a string with the error message
*/
async authenticateCustomer(
email: string,
password: string
): Promise<AuthenticateResult> {
return await this.atomicPhase_(async (transactionManager) => {
try {
const customer: Customer = await this.customerService_
.withTransaction(transactionManager)
.retrieveRegisteredByEmail(email, {
select: ["id", "password_hash"],
})
if (customer.password_hash) {
const passwordsMatch = await this.comparePassword_(
password,
customer.password_hash
)
if (passwordsMatch) {
const customer = await this.customerService_
.withTransaction(transactionManager)
.retrieveRegisteredByEmail(email)
return {
success: true,
customer,
}
}
}
} catch (error) {
// ignore
}
return {
success: false,
error: "Invalid email or password",
}
})
}
}
export default AuthService