Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ const post = await client.db.insert('posts', {
| `403 Insert denied` (ownerField `_id`) | `_id` is not a valid owner field for inserts | Change ownerField to `userId` or similar |
| `403 Owner field immutable` | Trying to change the owner field on update | Remove the owner field from the PATCH/PUT body |

## Public Signup

By default, new users can sign up using email/password or social providers. You can disable public signups from the **Authentication** page in the dashboard under the **Allow Public Signups** toggle. When disabled, the API blocks new registrations, allowing only existing users to log in.

---

## Social Auth
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ jest.mock('../controllers/project.controller', () => {
analytics: jest.fn(ok),
updateAllowedDomains: jest.fn(ok),
toggleAuth: jest.fn(ok),
togglePublicSignup: jest.fn(ok),
updateAuthProviders: jest.fn(ok),
updateCollectionRls: jest.fn(ok),
listMailTemplates: jest.fn(ok),
Expand Down
37 changes: 37 additions & 0 deletions apps/dashboard-api/src/controllers/project.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2553,6 +2553,43 @@ module.exports.toggleAuth = async (req, res) => {
}
};

module.exports.togglePublicSignup = async (req, res, next) => {
try {
const { projectId } = req.params;
const { enable } = req.body;

if (typeof enable !== "boolean") {
return next(new AppError(400, "enable parameter must be a boolean"));
}

const project = await Project.findOne({
_id: projectId,
...getProjectAccessQuery(req.user._id),
});
if (!project) return next(new AppError(404, "Project not found"));

project.allowPublicSignup = enable;
await project.save();
Comment thread
coderabbitai[bot] marked this conversation as resolved.

await deleteProjectById(projectId);
await deleteProjectByApiKeyCache(project.publishableKey);
await deleteProjectByApiKeyCache(project.secretKey);

const projectObj = sanitizeProjectResponse(project.toObject());

res.json({
success: true,
data: {
allowPublicSignup: project.allowPublicSignup,
project: projectObj,
},
message: `Public signup ${project.allowPublicSignup ? "enabled" : "disabled"} successfully`
});
} catch (err) {
next(err);
}
};

module.exports.updateAuthProviders = async (req, res) => {
try {
const { projectId } = req.params;
Expand Down
2 changes: 2 additions & 0 deletions apps/dashboard-api/src/routes/projects.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const {
analytics,
updateAllowedDomains,
toggleAuth,
togglePublicSignup,
updateAuthProviders,
updateCollectionRls,
listMailTemplates,
Expand Down Expand Up @@ -138,6 +139,7 @@ router.get('/:projectId/analytics', authMiddleware, authorizeProject(), analytic

// PATCH REQ FOR TOGGLE AUTH
router.patch('/:projectId/auth/toggle', authMiddleware, authorizeProject('admin'), verifyEmail, toggleAuth);
router.patch('/:projectId/auth/public-signup', authMiddleware, authorizeProject('admin'), verifyEmail, togglePublicSignup);

// PATCH REQ FOR SOCIAL AUTH PROVIDERS
router.patch('/:projectId/auth/providers', authMiddleware, authorizeProject('admin'), planEnforcement.attachDeveloper, verifyEmail, planEnforcement.checkByokGate, updateAuthProviders);
Expand Down
8 changes: 8 additions & 0 deletions apps/public-api/src/controllers/userAuth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,10 @@ const findOrCreateSocialUser = async ({ project, usersColConfig, Model, provider
return { user, isNewUser: false, linkedByEmail: true };
}

if (project.allowPublicSignup === false) {
throw new AppError(403, "Public signup is disabled for this project. Only existing users can log in.");
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const newUserPayload = await buildSocialAuthUserPayload(usersColConfig, profile);
newUserPayload[providerIdField] = profile.providerUserId;
newUserPayload.authProviders = [providerName];
Expand Down Expand Up @@ -988,6 +992,10 @@ module.exports.signup = async (req, res, next) => {
try {
const project = req.project;

if (project.allowPublicSignup === false) {
return next(new AppError(403, "Public signup is disabled for this project"));
}

const { email, password, username, ...otherData } = userSignupSchema.parse(req.body);
const normalizedEmail = email.toLowerCase().trim();

Expand Down
48 changes: 41 additions & 7 deletions apps/web-dashboard/src/pages/Auth.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export default function Auth() {
const [searchTerm, setSearchTerm] = useState('');
const [project, setProject] = useState(null);
const [isEnabling, setIsEnabling] = useState(false);
const [isTogglingSignup, setIsTogglingSignup] = useState(false);
const [isSavingProviders, setIsSavingProviders] = useState(false);
const [isSocialAuthModalOpen, setIsSocialAuthModalOpen] = useState(false);
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
Expand All @@ -60,6 +61,13 @@ export default function Auth() {
const githubCallbackUrl = `${PUBLIC_API_URL}/api/userAuth/social/github/callback`;
const googleCallbackUrl = `${PUBLIC_API_URL}/api/userAuth/social/google/callback`;

const myMember = project?.members?.find(m => {
const memberId = typeof m.user === 'object' ? m.user?._id : m.user;
return memberId?.toString() === user?._id?.toString() || m.email === user?.email;
});
const myRole = project?.owner?.toString() === user?._id?.toString() ? 'owner' : (myMember?.role || 'viewer');
const isViewer = myRole === 'viewer';

// Flow Logic
const usersCollection = project?.collections?.find(c => c.name === 'users');
const hasUserCollection = !!usersCollection;
Expand Down Expand Up @@ -148,6 +156,20 @@ export default function Auth() {
finally { setIsSavingProviders(false); }
};

const handleTogglePublicSignup = async (enable) => {
if (isTogglingSignup || isViewer) return;
setIsTogglingSignup(true);
try {
const res = await api.patch(`/api/projects/${projectId}/auth/public-signup`, { enable });
setProject(res.data.project);
toast.success(`Public signup ${enable ? 'enabled' : 'disabled'}`);
} catch (err) {
toast.error(err.response?.data?.message || 'Failed to toggle public signup');
} finally {
setIsTogglingSignup(false);
}
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const goToUsersSchemaPreset = () => {
navigate(`/project/${projectId}/create-collection?name=users&preset=auth-users`);
};
Expand Down Expand Up @@ -210,13 +232,6 @@ export default function Auth() {

if (loading) return <div className="container spinner"></div>;

const myMember = project?.members?.find(m => {
const memberId = typeof m.user === 'object' ? m.user?._id : m.user;
return memberId?.toString() === user?._id?.toString() || m.email === user?.email;
});
const myRole = project?.owner?.toString() === user?._id?.toString() ? 'owner' : (myMember?.role || 'viewer');
const isViewer = myRole === 'viewer';

return (
<div className="container" style={{ maxWidth: '1200px', margin: '0 auto', paddingBottom: '4rem' }}>
<AuthHeader
Expand Down Expand Up @@ -356,6 +371,25 @@ export default function Auth() {

<div style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}>
<SectionHeader title="Settings" />

<div className="glass-card" style={{ padding: '1.25rem', borderRadius: '12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<h4 style={{ fontSize: '0.85rem', fontWeight: 600, marginBottom: '4px' }}>Allow Public Signups</h4>
<p style={{ fontSize: '0.7rem', color: 'var(--color-text-muted)' }}>
When disabled, new users cannot sign up via API or OAuth. Only existing users can log in.
</p>
</div>
<label className="switch">
<input
type="checkbox"
checked={project?.allowPublicSignup !== false}
onChange={(e) => handleTogglePublicSignup(e.target.checked)}
disabled={isTogglingSignup || isViewer}
/>
<span className={`slider round ${(isTogglingSignup || isViewer) ? 'disabled' : ''}`}></span>
</label>
</div>

<SocialAuthConfig
authProviders={authProviders}
onOpenModal={() => setIsSocialAuthModalOpen(true)}
Expand Down
9 changes: 9 additions & 0 deletions mintlify/docs/guides/authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ All auth endpoints require your publishable key (`pk_live_...`) in the `x-api-ke

**Base URL:** `https://api.ub.bitbros.in`

## Disabling Public Signups

By default, any user can create an account. To block new registrations:
1. Navigate to your project dashboard.
2. Go to the **Authentication** page.
3. Turn off the **Allow Public Signups** toggle.

Once disabled, new signups will receive a `403 Forbidden` error, but existing users can still log in.

## The `users` collection contract

Before using authentication, create a collection named `users` in your project. It must include at least these two fields:
Expand Down
1 change: 1 addition & 0 deletions mintlify/docs/react-sdk/ur-auth.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export default function LoginPage() {
| `colors` | `Partial<AuthColors>` | `undefined` | Overrides for auth widget theme colors. |
| `branding` | `AuthBranding` | `undefined` | Branding/white-label configuration (logo, app name, subtitle, brand color). |
| `labels` | `Partial<AuthLabels>` | `undefined` | Text/copy overrides for tabs, titles, buttons, and footer prompts. |
| `hideSignup` | `boolean` | `false` | Hides the sign up tab and sign up footer toggle when true. |
| `onSuccess` | `() => void` | `undefined` | Called after successful sign-in or sign-up flow. |

> All customization props are optional. If omitted, `<UrAuth>` falls back to the same default behavior/UI style as v0.1.x.
Expand Down
1 change: 1 addition & 0 deletions packages/common/src/models/Project.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ const projectSchema = new mongoose.Schema(
required: true,
},
isAuthEnabled: { type: Boolean, default: false },
allowPublicSignup: { type: Boolean, default: true },
siteUrl: { type: String, default: "" },
/**
* Managed OAuth providers for project user authentication.
Expand Down
6 changes: 5 additions & 1 deletion sdks/urbackend-react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ import { UrAuth, GuestRoute } from '@urbackend/react';
export default function LoginPage() {
return (
<GuestRoute fallback={<div>Loading...</div>} onRedirect={() => window.location.href = '/dashboard'}>
<UrAuth providers={['google', 'github']} theme="light" />
<UrAuth
providers={['google', 'github']}
theme="light"
hideSignup={false} // Set to true to hide the signup tab
/>
</GuestRoute>
);
}
Expand Down
11 changes: 7 additions & 4 deletions sdks/urbackend-react/src/components/UrAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export interface UrAuthProps {
branding?: AuthBranding;
labels?: Partial<AuthLabels>;
onSuccess?: () => void;
hideSignup?: boolean;
}

const defaultLabels: AuthLabels = {
Expand Down Expand Up @@ -153,10 +154,11 @@ export const UrAuth: React.FC<UrAuthProps> = ({
colors,
branding,
labels,
onSuccess
onSuccess,
hideSignup = false
}) => {
const { login, signUp, socialLogin, requestPasswordReset, resetPassword, isLoading, error, clearError } = useAuth();
const [mode, setMode] = useState<'signin' | 'signup' | 'forgot' | 'reset'>('signin');
const [mode, setMode] = useState<'signin' | 'signup' | 'forgot' | 'reset'>(hideSignup ? 'signin' : 'signin');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [otp, setOtp] = useState('');
Expand Down Expand Up @@ -194,6 +196,8 @@ export const UrAuth: React.FC<UrAuthProps> = ({

const hasPasswordAuth = isEmailPasswordEnabled;
const hasSocialAuth = isGoogleEnabled || isGithubEnabled;

const showSwitcher = hasPasswordAuth && !hideSignup;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
const brandName = branding?.brandName || branding?.appName || branding?.title || 'urBackend';
const headerTitle = branding?.title || brandName;
const brandingLogo = branding?.logo ?? branding?.logoUrl;
Expand All @@ -204,7 +208,6 @@ export const UrAuth: React.FC<UrAuthProps> = ({
: mode === 'forgot'
? text.forgotTitle
: text.resetTitle);
const showSwitcher = hasPasswordAuth;

useEffect(() => {
if (error) {
Expand Down Expand Up @@ -651,7 +654,7 @@ export const UrAuth: React.FC<UrAuthProps> = ({
{(mode === 'signin' || mode === 'signup') && renderSocialButtons()}
</div>

{hasPasswordAuth && (
{hasPasswordAuth && (!hideSignup || mode !== 'signin') && (
<div style={styles.footer}>
{footerPrompt}
<button
Expand Down
Loading