Skip to content

Commit fb977ce

Browse files
committed
feat: update MagicLinkEmailStrategy to create user if not found and improve email context handling
1 parent 3db9c9c commit fb977ce

File tree

2 files changed

+12
-20
lines changed

2 files changed

+12
-20
lines changed

server/src/auth/strategies/magicLinkEmail.strategy.spec.ts

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,6 @@ describe('MagicLinkEmailStrategy', () => {
107107

108108
expect(mockUserService.findByEmail).toHaveBeenCalledWith(email);
109109

110-
expect(mockUserService.createWithEmail).toHaveBeenCalledWith(email);
111-
112110
expect(mockMailingService.sendEmail).toHaveBeenCalledWith({
113111
to: email,
114112
context: {
@@ -134,20 +132,21 @@ describe('MagicLinkEmailStrategy', () => {
134132
expect(result).toEqual(user);
135133
});
136134

137-
it('should log an error if user is not found', async () => {
135+
it('should create a new user if not found and return the user', async () => {
138136
const payload = { destination: '[email protected]' };
139137

140138
mockUserService.findByEmail.mockResolvedValue(null);
141-
142-
const loggerSpy = jest.spyOn(MagicLinkEmailStrategy.logger, 'error');
139+
mockUserService.createWithEmail.mockResolvedValue({
140+
141+
username: 'test',
142+
});
143143

144144
const result = await strategy.validate(payload);
145145

146-
expect(loggerSpy).toHaveBeenCalledWith(
147-
'User not found: [email protected]',
148-
);
149-
150-
expect(result).toBeNull();
146+
expect(result).toEqual({
147+
148+
username: 'test',
149+
});
151150
});
152151
});
153152
});

server/src/auth/strategies/magicLinkEmail.strategy.ts

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -53,17 +53,14 @@ export class MagicLinkEmailStrategy extends PassportStrategy(
5353
mailingService: MailingService,
5454
) =>
5555
async (email: string, magicLink: string) => {
56-
let user = await userService.findByEmail(email);
56+
const user = await userService.findByEmail(email);
5757

5858
if (!user) {
59-
// Create user if not found
60-
user = await userService.createWithEmail(email);
61-
6259
mailingService.sendEmail({
6360
to: email,
6461
context: {
6562
magicLink: magicLink,
66-
username: user.username,
63+
username: email.split('@')[0],
6764
},
6865
subject: 'Welcome to Noteblock.world',
6966
template: 'magic-link-new-account',
@@ -89,11 +86,7 @@ export class MagicLinkEmailStrategy extends PassportStrategy(
8986
const user = await this.userService.findByEmail(payload.destination);
9087

9188
if (!user) {
92-
MagicLinkEmailStrategy.logger.error(
93-
`User not found: ${payload.destination}`,
94-
);
95-
96-
return null;
89+
return await this.userService.createWithEmail(payload.destination);
9790
}
9891

9992
MagicLinkEmailStrategy.logger.debug(`User found: ${user.username}`);

0 commit comments

Comments
 (0)