@@ -114,13 +114,12 @@ export const apiKeyRouter = createTRPCRouter({
114114 requestIp,
115115 userAgent,
116116 } = ctx ;
117- const { keyId } = input ;
118117 const { user } = session ;
119118
120- const rotatedKey = await db . $transaction ( async ( tx ) => {
119+ const key = await db . $transaction ( async ( tx ) => {
121120 const existingKey = await tx . apiKey . findUnique ( {
122121 where : {
123- keyId,
122+ keyId : input . keyId ,
124123 active : true ,
125124 } ,
126125 } ) ;
@@ -132,11 +131,21 @@ export const apiKeyRouter = createTRPCRouter({
132131 } ) ;
133132 }
134133
135- await tx . apiKey . delete ( {
136- where : { keyId : existingKey . keyId } ,
137- } ) ;
134+ const token = createApiToken ( ) ;
135+ const keyId = generatePublicId ( ) ;
136+ const hashedToken = createSecureHash ( token ) ;
138137
139- const key = await createApiKeyHandler ( { tx, companyId, memberId } ) ;
138+ const newKey = await tx . apiKey . update ( {
139+ where : {
140+ id : existingKey . id ,
141+ membershipId : memberId ,
142+ } ,
143+ data : {
144+ keyId,
145+ hashedToken,
146+ active : true ,
147+ } ,
148+ } ) ;
140149
141150 await Audit . create (
142151 {
@@ -147,18 +156,18 @@ export const apiKeyRouter = createTRPCRouter({
147156 userAgent,
148157 requestIp,
149158 } ,
150- target : [ { type : "apiKey" , id : key . id } ] ,
151- summary : `${ user . name } rotated the apiKey ${ key . name } ` ,
159+ target : [ { type : "apiKey" , id : newKey . id } ] ,
160+ summary : `${ user . name } rotated the apiKey ${ newKey . name } ` ,
152161 } ,
153162 tx ,
154163 ) ;
155- return key ;
164+ return newKey ;
156165 } ) ;
157166
158167 return {
159- token : rotatedKey . hashedToken ,
160- keyId : rotatedKey . keyId ,
161- createdAt : rotatedKey . createdAt ,
168+ token : key . hashedToken ,
169+ keyId : key . keyId ,
170+ createdAt : key . createdAt ,
162171 } ;
163172 } catch ( error ) {
164173 console . error ( "Error rotating the api key :" , error ) ;
0 commit comments