Skip to content

Commit

Permalink
feat: auto sign-up and psuedo id
Browse files Browse the repository at this point in the history
  • Loading branch information
dotneet committed Apr 18, 2023
1 parent 854b564 commit 4afddc1
Show file tree
Hide file tree
Showing 7 changed files with 87 additions and 25 deletions.
1 change: 0 additions & 1 deletion .env.local.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
DEFAULT_MODEL=gpt-3.5-turbo
OPENAI_API_KEY=YOUR_KEY
NEXT_PUBLIC_DEFAULT_SYSTEM_PROMPT=You are ChatGPT, a large language model trained by OpenAI. Follow the user's instructions carefully. Respond using markdown.
NEXT_PUBLIC_API_URL=http://localhost:3000/

# Google Plugin
GOOGLE_API_KEY=YOUR_API_KEY
Expand Down
5 changes: 2 additions & 3 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ import { withAuth } from 'next-auth/middleware';
export default withAuth({
callbacks: {
async authorized({ token }) {
if (process.env.NEXTAUTH_ENABLED === 'false') {
if (process.env.NEXTAUTH_ENABLED === 'false' && token?.email) {
return true;
}

if (token?.name && !token?.email) {
if (!token?.email) {
return false;
} else {
const pattern = process.env.NEXTAUTH_EMAIL_PATTERN || '';
Expand Down
26 changes: 25 additions & 1 deletion pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
import NextAuth, { NextAuthOptions } from 'next-auth';
import NextAuth, { NextAuthOptions, PagesOptions } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import GithubProvider from 'next-auth/providers/github';
import GoogleProvider from 'next-auth/providers/google';

const providers = [];
if (process.env.NEXTAUTH_ENABLED === 'false') {
providers.push(
Credentials({
credentials: {
email: { label: 'Email', type: 'text' },
},
async authorize(credentials: any, req: any) {
const email = credentials.email.trim();
return {
id: 'a',
email,
};
},
}),
);
}
if (process.env.GOOGLE_CLIENT_ID) {
providers.push(
GoogleProvider({
Expand All @@ -20,9 +37,16 @@ if (process.env.GITHUB_CLIENT_ID) {
);
}

let pages: Partial<PagesOptions> = {};

if (process.env.NEXTAUTH_ENABLED === 'false') {
pages['signIn'] = '/auth/autologin';
}

export const authOptions: NextAuthOptions = {
providers: providers,
session: { strategy: 'jwt' },
pages,
};

export default NextAuth(authOptions);
59 changes: 59 additions & 0 deletions pages/auth/autologin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { getCsrfToken } from 'next-auth/react';
import { useEffect, useRef } from 'react';

import type {
GetServerSidePropsContext,
InferGetServerSidePropsType,
} from 'next';

import { v4 } from 'uuid';

const key = 'psuedo_uid';
const loginInfoKey = 'psuedo_login_info';
interface LoginInfo {
count: number;
lastTime: number;
}
export default function SignIn({
csrfToken,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
const ref = useRef<HTMLFormElement>(null);
useEffect(() => {
if (ref.current) {
const uuid = localStorage.getItem(key) || v4() + '@example.com';
const info = JSON.parse(
localStorage.getItem(loginInfoKey) || '{"count":0, "lastTime":0}',
) as LoginInfo;
const now = Math.floor(Date.now() / 1000);
if (info.lastTime < now - 60) {
info.count = 0;
info.lastTime = now;
}
if (info.count > 5) {
alert('Please check if NEXTAUTH_EMAIL_PATTERN permit [email protected]');
return;
}
localStorage.setItem(key, uuid);
localStorage.setItem(loginInfoKey, JSON.stringify(info));
const emailInput = ref.current.querySelector(
'input[name="email"]',
) as HTMLInputElement;
emailInput.value = uuid;
ref.current.submit();
}
}, [ref]);
return (
<form ref={ref} method="post" action="/api/auth/callback/credentials">
<input name="csrfToken" type="hidden" defaultValue={csrfToken} />
<input name="email" type="hidden" defaultValue="" />
</form>
);
}

export async function getServerSideProps(context: GetServerSidePropsContext) {
return {
props: {
csrfToken: await getCsrfToken(context),
},
};
}
16 changes: 0 additions & 16 deletions services/useApiService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,6 @@ export type PlanningRequestProps = PlanningRequest;
const useApiService = () => {
const fetchService = useFetch();

// const getModels = useCallback(
// (
// params: GetManagementRoutineInstanceDetailedParams,
// signal?: AbortSignal
// ) => {
// return fetchService.get<GetManagementRoutineInstanceDetailed>(
// `/v1/ManagementRoutines/${params.managementRoutineId}/instances/${params.instanceId
// }?sensorGroupIds=${params.sensorGroupId ?? ''}`,
// {
// signal,
// }
// );
// },
// [fetchService]
// );

const getModels = useCallback(
(params: GetModelsRequestProps, signal?: AbortSignal) => {
return fetchService.post<GetModelsRequestProps>(`/api/models`, {
Expand Down
2 changes: 1 addition & 1 deletion types/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export interface ProcessEnv {
OPENAI_API_TYPE?: 'openai' | 'azure';
OPENAI_API_VERSION?: string;
OPENAI_ORGANIZATION?: string;
NEXT_PUBLIC_API_URL: string;
NEXT_PUBLIC_DEFAULT_SYSTEM_PROMPT: string;
MONGODB_URI: string;
MONGODB_DB: string;
GITHUB_CLIENT_ID?: string;
Expand Down
3 changes: 0 additions & 3 deletions utils/server/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@ export const ensureHasValidSession = async (
req: NextApiRequest,
res: NextApiResponse,
): Promise<boolean> => {
if (process.env.NEXTAUTH_ENABLED === 'false') {
return true;
}
const session = await getServerSession(req, res, authOptions);
return session !== null;
};
Expand Down

0 comments on commit 4afddc1

Please sign in to comment.