Skip to content

Commit

Permalink
Merge pull request #907 from hngprojects/feat/fix-authentication
Browse files Browse the repository at this point in the history
Feat/fix authentication
  • Loading branch information
kinxlo authored Aug 4, 2024
2 parents cf061b5 + cb61e57 commit 4d88a42
Show file tree
Hide file tree
Showing 25 changed files with 192 additions and 195 deletions.
3 changes: 2 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ API_URL=https://your-teams-backend-url.com
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
AUTH_SECRET=
NEXTAUTH_URL=https://your-application-deployment
NEXTAUTH_URL=https://your-application-deployment
NODE_ENV="development" // change for deployment
6 changes: 4 additions & 2 deletions src/utils/createOrg.ts → src/actions/createOrg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@
import axios from "axios";
import * as z from "zod";

import { auth } from "~/lib/auth";
import { organizationSchema } from "~/schemas";
import { getApiUrl } from "./getApiUrl";

const team = process.env.TEAM;

export const createOrg = async (
values: z.infer<typeof organizationSchema>,
token: string,
token?: string,
) => {
const apiUrl = await getApiUrl();
const session = await auth();

const validatedFields = organizationSchema.safeParse(values);
if (!validatedFields.success) {
Expand All @@ -26,7 +28,7 @@ export const createOrg = async (
validatedFields.data,
{
headers: {
Authorization: `Bearer ${token}`,
Authorization: `Bearer ${session?.access_token || token}`,
},
},
);
Expand Down
File renamed without changes.
29 changes: 29 additions & 0 deletions src/actions/googleAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"use server";

import axios from "axios";

import { Profile, User } from "~/types";

interface AuthResponse {
data: User;
access_token: string;
}

const apiUrl = process.env.API_URL;

const googleAuth = async (profile: Profile): Promise<AuthResponse> => {
try {
const response = await axios.post(`${apiUrl}/api/v1/auth/google`, {
id_token: profile.id_token,
});

return {
data: response.data.user,
access_token: response.data.access_token,
};
} catch {
throw new Error("Authentication failed");
}
};

export { googleAuth };
69 changes: 69 additions & 0 deletions src/actions/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"use server";

import axios from "axios";
import { cookies } from "next/headers";
import * as z from "zod";

import { LoginSchema } from "~/schemas";

const apiUrl = process.env.API_URL;

export const loginUser = async (values: z.infer<typeof LoginSchema>) => {
const cookie = cookies();
const validatedFields = LoginSchema.safeParse(values);
if (!validatedFields.success) {
return {
error: "Login Failed. Please check your email and password.",
};
}
const { email, password } = validatedFields.data;
const payload = { email, password };
try {
const response = await axios.post(`${apiUrl}/api/v1/auth/login`, payload);
const access_token = response.data.access_token;

cookie.set("access_token", access_token, {
maxAge: 60 * 60 * 24 * 1,
httpOnly: true,
path: "/",
priority: "high",
});
return {
status: response.status,
};
} catch (error) {
return axios.isAxiosError(error) && error.response
? {
error: error.response.data.message || "Login failed.",
status: error.response.status,
}
: {
error: "An unexpected error occurred.",
};
}
};

export const nextlogin = async (values: z.infer<typeof LoginSchema>) => {
const validatedFields = LoginSchema.safeParse(values);
if (!validatedFields.success) {
return {
error: "Login Failed. Please check your email and password.",
};
}
const { email, password } = validatedFields.data;
const payload = { email, password };
try {
const response = await axios.post(`${apiUrl}/api/v1/auth/login`, payload);

return response.data;
} catch (error) {
return axios.isAxiosError(error) && error.response
? {
error: error.response.data.message || "Login failed.",
status: error.response.status,
}
: {
error: "An unexpected error occurred.",
};
}
};
24 changes: 9 additions & 15 deletions src/utils/registerAuth.ts → src/actions/register.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"use server";

import axios from "axios";
import { cookies } from "next/headers";
// import { cookies } from "next/headers";
import * as z from "zod";

import { OtpSchema, RegisterSchema } from "~/schemas";

const apiUrl = process.env.API_URL;
export const registerAuth = async (values: z.infer<typeof RegisterSchema>) => {
const cookie = cookies();

export const registerUser = async (values: z.infer<typeof RegisterSchema>) => {
const validatedFields = RegisterSchema.safeParse(values);
if (!validatedFields.success) {
return {
Expand All @@ -20,17 +20,11 @@ export const registerAuth = async (values: z.infer<typeof RegisterSchema>) => {
`${apiUrl}/api/v1/auth/register`,
validatedFields.data,
);
const access_token =
response.data.access_token ?? response.data.data.access_token;

cookie.set("access_token", access_token, {
maxAge: 60 * 60 * 24 * 1,
httpOnly: true,
path: "/",
priority: "high",
});

return response?.data?.user;
return {
status: response.status,
data: response.data,
};
} catch (error) {
return axios.isAxiosError(error) && error.response
? {
Expand All @@ -44,10 +38,10 @@ export const registerAuth = async (values: z.infer<typeof RegisterSchema>) => {
};

export const verifyOtp = async (values: z.infer<typeof OtpSchema>) => {
const otp = values.otp;
const token = values.token;
const email = values.email;

const payload = { otp: Number(otp), token: token };
const payload = { token, email };

try {
const response = await axios.post(
Expand Down
File renamed without changes.
6 changes: 3 additions & 3 deletions src/app/(auth-routes)/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { useEffect, useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";

import { getApiUrl } from "~/actions/getApiUrl";
import { loginUser } from "~/actions/login";
import CustomButton from "~/components/common/common-button/common-button";
import { Input } from "~/components/common/input";
import LoadingSpinner from "~/components/miscellaneous/loading-spinner";
Expand All @@ -24,8 +26,6 @@ import {
import { useToast } from "~/components/ui/use-toast";
import { cn } from "~/lib/utils";
import { LoginSchema } from "~/schemas";
import { getApiUrl } from "~/utils/getApiUrl";
import { loginAuth } from "~/utils/loginAuth";

const Login = () => {
const router = useRouter();
Expand Down Expand Up @@ -66,7 +66,7 @@ const Login = () => {

const onSubmit = async (values: z.infer<typeof LoginSchema>) => {
startTransition(async () => {
await loginAuth(values).then(async (data) => {
await loginUser(values).then(async (data) => {
const { email, password } = values;

if (data) {
Expand Down
4 changes: 2 additions & 2 deletions src/app/(auth-routes)/register/organisation/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useTransition } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

import { createOrg } from "~/actions/createOrg";
import LoadingSpinner from "~/components/miscellaneous/loading-spinner";
import { Button } from "~/components/ui/button";
import {
Expand All @@ -28,7 +29,6 @@ import {
} from "~/components/ui/select";
import { useToast } from "~/components/ui/use-toast";
import { organizationSchema } from "~/schemas";
import { createOrg } from "~/utils/createOrg";

function Organisation() {
const router = useRouter();
Expand Down Expand Up @@ -57,7 +57,7 @@ function Organisation() {
const onSubmit = async (values: z.infer<typeof organizationSchema>) => {
const token = sessionStorage.getItem("temp_token");
startTransition(async () => {
await createOrg(values, token || "").then(async (data) => {
await createOrg(values, token ?? "").then(async (data) => {
if (data.status === 201) {
router.push("/login");
}
Expand Down
8 changes: 4 additions & 4 deletions src/app/(auth-routes)/register/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { useEffect, useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";

import { getApiUrl } from "~/actions/getApiUrl";
import { registerUser } from "~/actions/register";
import CustomButton from "~/components/common/common-button/common-button";
import { Input } from "~/components/common/input";
import LoadingSpinner from "~/components/miscellaneous/loading-spinner";
Expand All @@ -23,8 +25,6 @@ import {
import { useToast } from "~/components/ui/use-toast";
import { cn } from "~/lib/utils";
import { RegisterSchema } from "~/schemas";
import { getApiUrl } from "~/utils/getApiUrl";
import { registerAuth } from "~/utils/registerAuth";

const Register = () => {
const router = useRouter();
Expand Down Expand Up @@ -66,9 +66,9 @@ const Register = () => {

const onSubmit = async (values: z.infer<typeof RegisterSchema>) => {
startTransition(async () => {
await registerAuth(values).then(async (data) => {
await registerUser(values).then(async (data) => {
if (data) {
sessionStorage.setItem("temp_token", data.access_token);
sessionStorage.setItem("temp_token", data.data);
router.push("/register/organisation");
}

Expand Down
2 changes: 1 addition & 1 deletion src/app/(landing-routes)/(home)/pricing/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";

import { getApiUrl } from "~/actions/getApiUrl";
import FaqAccordion from "~/components/layouts/accordion/FaqsAccordion";
import Heading from "~/components/layouts/heading";
import PricingCardSkeleton from "~/components/skeleton/pricingcardskeleton";
import { Button } from "~/components/ui/button";
import { faqData } from "~/constants/faqsdata";
import { getApiUrl } from "~/utils/getApiUrl";

interface BillingPlan {
id: string;
Expand Down
2 changes: 1 addition & 1 deletion src/app/(landing-routes)/career/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import axios from "axios";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

import { getApiUrl } from "~/actions/getApiUrl";
import CareerCardParent from "~/components/common/CareerCard";
import { Job } from "~/components/common/CareerCard/Jobs";
import Heading from "~/components/layouts/heading";
import Pagination from "~/components/layouts/pagination/Pagination";
import JobSkeleton from "~/components/skeleton/jobskeleton";
import { useToast } from "~/components/ui/use-toast";
import { getApiUrl } from "~/utils/getApiUrl";
import Nojobs from "./Nojobs";

export default function Career() {
Expand Down
2 changes: 1 addition & 1 deletion src/app/(landing-routes)/squeeze/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
import { z, ZodError } from "zod";

import { getApiUrl } from "~/actions/getApiUrl";
import { useToast } from "~/components/ui/use-toast";
import { getApiUrl } from "~/utils/getApiUrl";

const validationSchema = z.object({
first_name: z.string().min(1, "First name is required"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import { Check, ChevronLeft } from "lucide-react";
import { getSession } from "next-auth/react";
import { useState } from "react";

import { getApiUrl } from "~/actions/getApiUrl";
import CustomButton from "~/components/common/common-button/common-button";
import NotificationSettingSavedModal from "~/components/common/modals/notification-settings-saved";
import { useToast } from "~/components/ui/use-toast";
import { getApiUrl } from "~/utils/getApiUrl";
import { useNotificationStore } from "./_action/notification-store";
import NotificationHeader from "./_components/header";
import { NotificationSwitchBox } from "./_components/notification-switch-box";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from "axios";

import { getApiUrl } from "~/utils/getApiUrl";
import { getApiUrl } from "~/actions/getApiUrl";

export const exportMembersEndpoint = async (format: string = "csv") => {
const apiUrl = await getApiUrl();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import { useEffect, useState } from "react";

import { getApiUrl } from "~/actions/getApiUrl";
import CustomButton from "~/components/common/common-button/common-button";
import RoleCreationModal from "~/components/common/modals/role-creation";
import LoadingSpinner from "~/components/miscellaneous/loading-spinner";
import { useToast } from "~/components/ui/use-toast";
import { getApiUrl } from "~/utils/getApiUrl";

type Role = {
id: number;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import axios from "axios";
import { useEffect, useState } from "react";

import { getApiUrl } from "~/actions/getApiUrl";
import { useToast } from "~/components/ui/use-toast";
import { getApiUrl } from "~/utils/getApiUrl";

const useApiUrl = () => {
const [apiUrl, setApiUrl] = useState<string>("");
Expand Down
2 changes: 1 addition & 1 deletion src/components/layouts/navbar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";

import useVersionSync from "~/actions/useVersionSync";
import UserCard from "~/components/card/user-card";
import Logo from "~/components/common/logo";
import { cn } from "~/lib/utils";
import useVersionSync from "~/utils/useVersionSync";
import { NAV_LINKS } from "./links";
import MobileNav from "./mobile-navbar";

Expand Down
Loading

0 comments on commit 4d88a42

Please sign in to comment.