51 lines
1.2 KiB
TypeScript
51 lines
1.2 KiB
TypeScript
import { auth0Integration } from "@/integrations"
|
|
import { User } from "@/models"
|
|
import { Op } from "@sequelize/core"
|
|
import BaseService from "@/services/base-service"
|
|
import { Users } from "@/services"
|
|
|
|
export class EnsureFromAuth0TokenService extends BaseService {
|
|
constructor(private token: string) {
|
|
super()
|
|
}
|
|
|
|
async perform(): Promise<User> {
|
|
const { auth0Subject, email, firstName, lastName } = await auth0Integration.getUserInfo(
|
|
this.token
|
|
)
|
|
|
|
const existingUser = await User.withScope(["asCurrentUser"]).findOne({
|
|
where: { auth0Subject },
|
|
})
|
|
|
|
if (existingUser) {
|
|
return existingUser
|
|
}
|
|
|
|
const firstTimeUser = await User.withScope(["asCurrentUser"]).findOne({
|
|
where: { [Op.or]: [{ auth0Subject: email }, { email: email }] },
|
|
})
|
|
|
|
if (firstTimeUser) {
|
|
await firstTimeUser.update({ auth0Subject })
|
|
return firstTimeUser
|
|
}
|
|
|
|
await Users.CreateService.perform({
|
|
auth0Subject,
|
|
email,
|
|
firstName,
|
|
lastName,
|
|
})
|
|
|
|
const newUser = await User.withScope(["asCurrentUser"]).findOne({
|
|
where: { auth0Subject },
|
|
rejectOnEmpty: true,
|
|
})
|
|
|
|
return newUser
|
|
}
|
|
}
|
|
|
|
export default EnsureFromAuth0TokenService
|