fix: change sessionstate type to prevent unset values

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2023-03-19 22:04:28 +01:00
parent f78fd69bf4
commit 229d4a4a1d
6 changed files with 26 additions and 27 deletions

View file

@ -15,14 +15,15 @@ import { GuestAccess } from '../config/guest_access.enum';
import noteConfiguration, { NoteConfig } from '../config/note.config';
import { NotInDBError } from '../errors/errors';
import { ConsoleLoggerService } from '../logger/console-logger.service';
import { SessionState } from '../session/session.service';
import { User } from '../users/user.entity';
import { UsersService } from '../users/users.service';
/**
* This guard checks if a session is present.
*
* If there is a username in `request.session.user` it will try to get this user from the database and put it into `request.user`. See {@link RequestUser}.
* If there is no `request.session.user`, but any GuestAccess is configured, `request.session.authProvider` is set to `guest` to indicate a guest user.
* If there is a username in `request.session.username` it will try to get this user from the database and put it into `request.user`. See {@link RequestUser}.
* If there is no `request.session.username`, but any GuestAccess is configured, `request.session.authProvider` is set to `guest` to indicate a guest user.
*
* @throws UnauthorizedException
*/
@ -39,28 +40,25 @@ export class SessionGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request: Request & {
session?: { user: string; authProvider: string };
session?: SessionState;
user?: User;
} = context.switchToHttp().getRequest();
if (!request.session?.user) {
if (this.noteConfig.guestAccess !== GuestAccess.DENY) {
if (request.session) {
request.session.authProvider = 'guest';
return true;
}
const username = request.session?.username;
if (!username) {
if (this.noteConfig.guestAccess !== GuestAccess.DENY && request.session) {
request.session.authProvider = 'guest';
return true;
}
this.logger.debug('The user has no session.');
throw new UnauthorizedException("You're not logged in");
}
try {
request.user = await this.userService.getUserByUsername(
request.session.user,
);
request.user = await this.userService.getUserByUsername(username);
return true;
} catch (e) {
if (e instanceof NotInDBError) {
this.logger.debug(
`The user '${request.session.user}' does not exist, but has a session.`,
`The user '${username}' does not exist, but has a session.`,
);
throw new UnauthorizedException("You're not logged in");
}