Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions apps/public-api/src/__tests__/userAuth.social.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -690,4 +690,61 @@ describe('public userAuth social auth', () => {
expect(res.redirect).toHaveBeenCalledWith(expect.stringContaining('error='));
expect(res.redirect).toHaveBeenCalledWith(expect.stringContaining('deletion'));
});

test('handleSocialAuthCallback handles ValidationError on create by saving with validateBeforeSave: false', async () => {
redis.get.mockResolvedValueOnce(JSON.stringify({
projectId: 'project_1',
provider: 'github',
callbackUrl: 'http://localhost:5173/auth/callback',
}));
mockProjectFindByIdChain.lean.mockResolvedValueOnce(makeProject());

mockUsersModel.findOne
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(null);

const mockSave = jest.fn().mockResolvedValue(undefined);
class MockModel {
constructor(payload) {
Object.assign(this, payload);
this._id = 'mocked_user_id';
}
}
MockModel.prototype.save = mockSave;
MockModel.findOne = jest.fn()
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(null);
MockModel.create = jest.fn().mockImplementation(() => {
const error = new Error('users validation failed: customField: Path `customField` is required.');
error.name = 'ValidationError';
throw error;
});

const { getCompiledModel } = require('@urbackend/common');
getCompiledModel.mockReturnValueOnce(MockModel);

global.fetch
.mockResolvedValueOnce({
ok: true,
json: async () => ({ access_token: 'github_access_token' }),
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({ id: 123, login: 'alice', avatar_url: '' }),
})
.mockResolvedValueOnce({
ok: true,
json: async () => ([{ email: 'alice@example.com', verified: true, primary: true }]),
});

const req = makeReq({ params: { provider: 'github' }, query: { code: 'code_1', state: 'state_1' } });
const res = makeRes();

await controller.handleSocialAuthCallback(req, res);

expect(MockModel.create).toHaveBeenCalled();
expect(mockSave).toHaveBeenCalledWith({ validateBeforeSave: false });
expect(res.redirect).toHaveBeenCalledWith(expect.stringContaining('/auth/callback?'));
expect(res.redirect).toHaveBeenCalledWith(expect.stringContaining('userId=mocked_user_id'));
});
});
22 changes: 21 additions & 1 deletion apps/public-api/src/controllers/userAuth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,27 @@ const findOrCreateSocialUser = async ({ project, usersColConfig, Model, provider
newUserPayload.avatarUrl = profile.avatarUrl;
}

user = await Model.create(newUserPayload);
try {
user = await Model.create(newUserPayload);
} catch (err) {
if (err.name === 'ValidationError') {
try {
if (typeof Model === 'function') {
const doc = new Model(newUserPayload);
await doc.save({ validateBeforeSave: false });
user = doc;
} else {
user = await Model.create(newUserPayload);
}
} catch (saveErr) {
const validationError = new Error(`Validation failed during social signup: ${err.message}`);
validationError.statusCode = 400;
throw validationError;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
} else {
throw err;
}
Comment thread
yash-pouranik marked this conversation as resolved.
}
return { user, isNewUser: true, linkedByEmail: false };
};

Expand Down
26 changes: 0 additions & 26 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading