Skip to content

Commit

Permalink
fix: optional auth
Browse files Browse the repository at this point in the history
  • Loading branch information
NextFire committed Nov 10, 2023
1 parent ecaf33e commit 51ab277
Showing 1 changed file with 71 additions and 60 deletions.
131 changes: 71 additions & 60 deletions server/middlewares/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import tracer, {
addTags,
getRootSpanFromRequestContext,
} from "@server/logging/tracer";
import { User, Team, ApiKey } from "@server/models";
import { ApiKey, Team, User } from "@server/models";
import { AppContext, AuthenticationType } from "@server/types";
import { getUserForJWT } from "@server/utils/jwt";
import {
Expand All @@ -19,8 +19,7 @@ type AuthenticationOptions = {
/** A member or admin user role is required to access the route */
member?: boolean;
/**
* Authentication is parsed, but optional. Note that if a token is provided
* in the request it must be valid or the requst will be rejected.
* Authentication is parsed, but optional.
*/
optional?: boolean;
};
Expand Down Expand Up @@ -57,11 +56,13 @@ export default function auth(options: AuthenticationOptions = {}) {
token = ctx.cookies.get("accessToken");
}

if (!token && options.optional !== true) {
if (!token && !options.optional) {
throw AuthenticationError("Authentication required");
}

let user: User | null;
ctx.state.auth = {};

let user: User | null = null;
let type: AuthenticationType;

if (token) {
Expand All @@ -76,78 +77,88 @@ export default function auth(options: AuthenticationOptions = {}) {
},
});
} catch (err) {
throw AuthenticationError("Invalid API key");
if (!options.optional) {
throw AuthenticationError("Invalid API key");
}
}

if (!apiKey) {
if (!apiKey && !options.optional) {
throw AuthenticationError("Invalid API key");
}

user = await User.findByPk(apiKey.userId, {
include: [
{
model: Team,
as: "team",
required: true,
},
],
});
if (apiKey) {
user = await User.findByPk(apiKey.userId, {
include: [
{
model: Team,
as: "team",
required: true,
},
],
});

if (!user) {
throw AuthenticationError("Invalid API key");
if (!user && !options.optional) {
throw AuthenticationError("Invalid API key");
}
}
} else {
type = AuthenticationType.APP;
user = await getUserForJWT(String(token));
try {
user = await getUserForJWT(String(token));
} catch (err) {
if (!options.optional) {
throw err;
}
}
}

if (user.isSuspended) {
const suspendingAdmin = await User.findOne({
where: {
id: user.suspendedById,
},
paranoid: false,
});
throw UserSuspendedError({
adminEmail: suspendingAdmin?.email || undefined,
});
}
if (user) {
if (user.isSuspended) {
const suspendingAdmin = await User.findOne({
where: {
id: user.suspendedById,
},
paranoid: false,
});
throw UserSuspendedError({
adminEmail: suspendingAdmin?.email || undefined,
});
}

if (options.admin) {
if (!user.isAdmin) {
throw AuthorizationError("Admin role required");
if (options.admin) {
if (!user.isAdmin) {
throw AuthorizationError("Admin role required");
}
}
}

if (options.member) {
if (user.isViewer) {
throw AuthorizationError("Member role required");
if (options.member) {
if (user.isViewer) {
throw AuthorizationError("Member role required");
}
}
}

// not awaiting the promise here so that the request is not blocked
user.updateActiveAt(ctx).catch((err) => {
Logger.error("Failed to update user activeAt", err);
});

ctx.state.auth = {
user,
token: String(token),
type,
};

if (tracer) {
addTags(
{
"request.userId": user.id,
"request.teamId": user.teamId,
"request.authType": type,
},
getRootSpanFromRequestContext(ctx)
);
// not awaiting the promise here so that the request is not blocked
user.updateActiveAt(ctx).catch((err) => {
Logger.error("Failed to update user activeAt", err);
});

ctx.state.auth = {
user,
token: String(token),
type,
};

if (tracer) {
addTags(
{
"request.userId": user.id,
"request.teamId": user.teamId,
"request.authType": type,
},
getRootSpanFromRequestContext(ctx)
);
}
}
} else {
ctx.state.auth = {};
}

return next();
Expand Down

0 comments on commit 51ab277

Please sign in to comment.