1- import { User } from "../interfaces/tables/user" ;
1+ import { User , ApiKey } from "../interfaces/tables/user" ;
22import { Organization } from "../interfaces/tables/organization" ;
33import {
44 ErrorCode ,
@@ -148,15 +148,36 @@ const canUserGeneral = async (user: User, action: Authorizations) => {
148148 return false ;
149149} ;
150150
151+ const canUserApiKey = async (
152+ user : User ,
153+ action : Authorizations ,
154+ target : ApiKey
155+ ) => {
156+ // A user can do anything to her API key
157+ if ( target . userId == user . id ) return true ;
158+
159+ let secureAction = action ;
160+ if ( action === Authorizations . CREATE )
161+ secureAction = Authorizations . CREATE_SECURE ;
162+ if ( action === Authorizations . READ ) secureAction = Authorizations . READ_SECURE ;
163+ if ( action === Authorizations . UPDATE )
164+ secureAction = Authorizations . UPDATE_SECURE ;
165+ if ( action === Authorizations . DELETE )
166+ secureAction = Authorizations . DELETE_SECURE ;
167+
168+ const owner = await getUser ( target . userId ) ;
169+ return await canUserUser ( user , secureAction , owner ) ;
170+ } ;
171+
151172/**
152173 * Whether a user has authorization to perform an action
153174 * @param ipAddress IP address for the new location
154175 */
155176export const can = async (
156177 user : User | number ,
157178 action : Authorizations ,
158- targetType : "user" | "organization" | "membership" | "general" ,
159- target ?: User | Organization | Membership | number
179+ targetType : "user" | "organization" | "membership" | "api-key" | " general",
180+ target ?: User | Organization | Membership | ApiKey | number
160181) => {
161182 let userObject ;
162183 if ( typeof user === "number" ) {
@@ -165,7 +186,10 @@ export const can = async (
165186 userObject = user ;
166187 }
167188 let targetObject ;
168- if ( typeof target === "string" ) target = parseInt ( target ) ;
189+ if ( typeof target === "string" ) {
190+ let newTarget = parseInt ( target ) ;
191+ if ( ! isNaN ( newTarget ) ) target = newTarget ;
192+ }
169193 if ( typeof target == "number" ) {
170194 if ( targetType === "user" ) {
171195 targetObject = await getUser ( target ) ;
@@ -188,6 +212,8 @@ export const can = async (
188212 return await canUserMembership ( userObject , action , < Membership > (
189213 targetObject
190214 ) ) ;
215+ } else if ( targetType === "api-key" ) {
216+ return await canUserApiKey ( userObject , action , < ApiKey > targetObject ) ;
191217 } else {
192218 return await canUserGeneral ( userObject , action ) ;
193219 }
0 commit comments