Skip to content

Commit

Permalink
added login,register, github oauth, update name passwords
Browse files Browse the repository at this point in the history
  • Loading branch information
wpsadi committed Nov 16, 2024
1 parent 8a96131 commit a09acca
Show file tree
Hide file tree
Showing 27 changed files with 763 additions and 3 deletions.
4 changes: 4 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Appwrite
APPWRITE_PROJECT_ID = "5f5f3d5d5f5f3"
APPWRITE_ENDPOINT = "https://appwrite.io/v1"
APPWRITE_KEY = "G"
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ yarn-debug.log*
yarn-error.log*

# env files (can opt-in for commiting if needed)
.env*
.env.local

# vercel
.vercel
Expand Down
61 changes: 61 additions & 0 deletions app/api/auth/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { NextRequest } from "next/server";
import { AppwriteException } from "node-appwrite";

import { ClientAW, RootAW } from "@/appwrite_configs/config";
import { SetAuthCookie } from "@/helpers/sessionCookieFunctions";
import { loginSchema } from "@/validations/auth/loginSchema";

import { errorHandler, successHandler } from "../../handler";

export async function POST(req: NextRequest) {
try {
let body = {};
try {
body = (await req.json()) || {};
} catch {
throw new AppwriteException("No body passed", 400);
}

const validation = await loginSchema.safeParse(body);
if (!validation.success) {
throw new AppwriteException(validation.error.errors[0].message, 400);
}
const validatedData = validation.data;

// Register user with validated data
const { account: acccountRoot } = await RootAW();


// creating sesssion
const session = await acccountRoot.createEmailPasswordSession(
validatedData.email,
validatedData.password
);



const sessionKey = session.secret;

// setting the cookie
await SetAuthCookie(sessionKey);


const {account:SavedUserAccount} = await ClientAW();

const user = await SavedUserAccount.get();


// return the user
return successHandler({
user: {
id: user.$id,
email: user.email,
name: user.name,
registrationDate: user.registration,
verified: user.emailVerification,
}
});
} catch (e) {
return errorHandler(e);
}
}
7 changes: 7 additions & 0 deletions app/api/auth/oauth/github/login/failure/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { AppwriteException } from "node-appwrite";

import { errorHandler } from "@/app/api/handler";

export function GET() {
return errorHandler(new AppwriteException("Github login failed", 400));
}
21 changes: 21 additions & 0 deletions app/api/auth/oauth/github/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import * as sdk from "node-appwrite";

import { errorHandler } from "@/app/api/handler";
import { ClientAW } from "@/appwrite_configs/config";

export async function GET() {
try {
const { account } = await ClientAW(false);
const result = await account.createOAuth2Token(
sdk.OAuthProvider.Github, // provider
"http://localhost:3000/api/auth/oauth/github/login/success", // success (optional)
"http://localhost:3000/api/auth/oauth/github/login/failure", // failure (optional)
[] // scopes (optional)
);

return NextResponse.redirect(result);
} catch (e) {
return errorHandler(e);
}
}
51 changes: 51 additions & 0 deletions app/api/auth/oauth/github/login/success/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { NextRequest } from "next/server";
import { AppwriteException } from "node-appwrite";

import { errorHandler, successHandler } from "@/app/api/handler";
import { ClientAW, RootAW } from "@/appwrite_configs/config";
import { SetAuthCookie } from "@/helpers/sessionCookieFunctions";

export async function GET(req: NextRequest) {
try {
const queryStore = req.nextUrl.searchParams;

const isPresent = queryStore.has("secret") && queryStore.has("userId");

if (!isPresent) {
return errorHandler(
new AppwriteException("userId or secret not present", 400)
);
}

const secret = queryStore.get("secret") as string;
const userId = queryStore.get("userId") as string;

const { account: accountRoot } = await RootAW();
const session = await accountRoot.createSession(userId, secret);

const sessionKey = session.secret;

// setting the cookie
await SetAuthCookie(sessionKey);

const { account: SavedUserAccount } = await ClientAW();

const user = await SavedUserAccount.get();

return successHandler(
{
user: {
id: user.$id,
email: user.email,
name: user.name,
registrationDate: user.registration,
verified: user.emailVerification,
},
},
"Github login successful",
200
);
} catch (e) {
return errorHandler(e);
}
}
7 changes: 7 additions & 0 deletions app/api/auth/oauth/github/register/failure/route.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { AppwriteException } from "node-appwrite";

import { errorHandler } from "@/app/api/handler";

export function GET() {
return errorHandler(new AppwriteException("Github registration failed", 400));
}
21 changes: 21 additions & 0 deletions app/api/auth/oauth/github/register/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import * as sdk from "node-appwrite";

import { errorHandler } from "@/app/api/handler";
import { ClientAW } from "@/appwrite_configs/config";

export async function GET() {
try {
const { account } = await ClientAW(false);
const result = await account.createOAuth2Token(
sdk.OAuthProvider.Github, // provider
"http://localhost:3000/api/auth/oauth/github/register/success", // success (optional)
"http://localhost:3000/api/auth/oauth/github/register/failure", // failure (optional)
[] // scopes (optional)
);

return NextResponse.redirect(result);
} catch (e) {
return errorHandler(e);
}
}
51 changes: 51 additions & 0 deletions app/api/auth/oauth/github/register/success/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { NextRequest } from "next/server";
import { AppwriteException } from "node-appwrite";

import { errorHandler, successHandler } from "@/app/api/handler";
import { ClientAW, RootAW } from "@/appwrite_configs/config";
import { SetAuthCookie } from "@/helpers/sessionCookieFunctions";

export async function GET(req: NextRequest) {
try {
const queryStore = req.nextUrl.searchParams;

const isPresent = queryStore.has("secret") && queryStore.has("userId");

if (!isPresent) {
return errorHandler(
new AppwriteException("userId or secret not present", 400)
);
}

const secret = queryStore.get("secret") as string;
const userId = queryStore.get("userId") as string;

const { account: accountRoot } = await RootAW();
const session = await accountRoot.createSession(userId, secret);

const sessionKey = session.secret;

// setting the cookie
await SetAuthCookie(sessionKey);

const { account: SavedUserAccount } = await ClientAW();

const user = await SavedUserAccount.get();

return successHandler(
{
user: {
id: user.$id,
email: user.email,
name: user.name,
registrationDate: user.registration,
verified: user.emailVerification,
},
},
"Github login successful",
200
);
} catch (e) {
return errorHandler(e);
}
}
65 changes: 65 additions & 0 deletions app/api/auth/register/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type { NextRequest } from "next/server";
import { AppwriteException, ID } from "node-appwrite";

import { ClientAW, RootAW } from "@/appwrite_configs/config";
import { SetAuthCookie } from "@/helpers/sessionCookieFunctions";
import { registerSchema } from "@/validations/auth/registerSchema";

import { errorHandler, successHandler } from "../../handler";

export async function POST(req: NextRequest) {
try {
let body = {};
try{
body = await req.json() || {};
}catch{
throw new AppwriteException("No body passed", 400);
}

const validation = await registerSchema.safeParse(body);
if (!validation.success) {
throw new AppwriteException(validation.error.errors[0].message, 400);
}
const validatedData = validation.data;

// Register user with validated data
const { account } = await ClientAW(false);
const { account: acccountRoot } = await RootAW();

// creating account
const user = await account.create(
ID.unique(),
validatedData.email,
validatedData.password,
validatedData.name
);

// creating sesssion
const session = await acccountRoot.createEmailPasswordSession(
validatedData.email,
validatedData.password
);
const sessionKey = session.secret;

// setting the cookie
await SetAuthCookie(sessionKey);

const { account: SavedUserAccount } = await ClientAW();
// sending email
await SavedUserAccount.createVerification("http://localhost:3000/api/user/email/verify");

// return the user
return successHandler({
user: {
id: user.$id,
email: user.email,
name: user.name,
verified: user.emailVerification,
registrationDate: user.registration,
}
});
} catch (e) {
return errorHandler(e);
}
}

62 changes: 62 additions & 0 deletions app/api/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { NextResponse } from "next/server";
import { AppwriteException } from "node-appwrite";

export const errorHandler = (error: unknown) => {
if (error instanceof AppwriteException) {
return NextResponse.json(
{
success: false,
mode: process.env.NODE_ENV as string,
status: error.code,
message: error.message,
},
{
status: error.code || 500,
}
);
}

if (error instanceof Error) {
return NextResponse.json(
{
success: false,
mode: process.env.NODE_ENV as string,
status: 500,
message: error.message,
},
{
status: 500,
}
);
}

return NextResponse.json(
{
success: false,
mode: process.env.NODE_ENV as string,
status: 500,
message: "An unknown error occurred",
},
{
status: 500,
}
);
};

export const successHandler = (
data: object | string,
message?: string,
code?: number
) => {
return NextResponse.json(
{
success: true,
message: message || "Successful",
mode: process.env.NODE_ENV as string,
data: data,
},
{
status: code || 200,
}
);
};
17 changes: 17 additions & 0 deletions app/api/user/email/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ClientAW } from "@/appwrite_configs/config";

import { errorHandler, successHandler } from "../../handler";

export async function GET() {
try {
const { account } = await ClientAW(true);
const user= await account.get();
return successHandler({
id: user.$id,
email: user.email,
verified: user.emailVerification,
},"Email Info",200);
} catch (e) {
return errorHandler(e);
}
}
Loading

0 comments on commit a09acca

Please sign in to comment.