Skip to content

Commit 72d5075

Browse files
committed
completed signup
Signed-off-by: Omkar Phansopkar <[email protected]>
1 parent 91b7b61 commit 72d5075

File tree

10 files changed

+155
-34
lines changed

10 files changed

+155
-34
lines changed

.env

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
NEXT_PUBLIC_REACT_APP_API_KEY = 08387dfc64msh94f0df087928182p1213afjsn3aa4359e369c
2-
NEXT_APP_SERVER_URL=http://localhost:5000
2+
NEXT_APP_SERVER_URL=http://localhost:5001

server/constants/config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const config = {
2-
PORT: process.env.PORT || 5000,
2+
PORT: process.env.PORT || 5001,
33
JWT_SECRET: process.env.JWT_SECRET || "mysecret",
44
MONGODB_SRV_STRING: process.env.MONGODB_SRV_STRING || "gg",
55
}

server/models/OwnerSchema.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@ const ownerSchema = new mongoose.Schema({
1414
phone: {
1515
type: String,
1616
required: true,
17-
unique: true,
17+
// unique: true,
1818
},
1919
gstin: {
2020
type: String,
2121
required: true,
22-
unique: true,
22+
// unique: true,
2323
},
2424
password: {
2525
type: String,

server/routes/auth.js

Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,21 @@ const jwt = require('jsonwebtoken');
66
const { Owner } = require("../models/OwnerSchema");
77
const { JWT_SECRET } = require('../constants/config');
88

9+
10+
function prepareJWT(owner){
11+
return jwt.sign(
12+
{
13+
_id: owner._id,
14+
restaurant_name: owner.restaurant_name,
15+
address: owner.address,
16+
phone: owner.phone,
17+
gstin: owner.gstin,
18+
},
19+
JWT_SECRET,
20+
{ expiresIn: '2d' }
21+
);
22+
}
23+
924
router.post('/api/auth/signup', async (req, res) => {
1025
try {
1126
// Check for mandatory fields
@@ -19,12 +34,35 @@ router.post('/api/auth/signup', async (req, res) => {
1934

2035
// Create new owner object
2136
const owner = new Owner(req.body);
37+
38+
console.log("New owner", owner);
2239

2340
// Save owner to database
2441
const savedOwner = await owner.save();
25-
26-
// Return success response with ID of new owner
27-
res.status(201).json({ message: 'New owner created successfully', id: savedOwner._id });
42+
43+
// Prepare the JWT with the owner's fields
44+
const token = prepareJWT(savedOwner);
45+
46+
// Send the JWT in a cookie
47+
// res.cookie('jwt', token, {
48+
// // httpOnly: true,
49+
// maxAge: 2 * 24 * 60 * 60 * 1000, // 2 days
50+
// sameSite: 'lax',
51+
// });
52+
53+
// Return a success response with the owner's fields
54+
return res.status(201).json({
55+
success: true,
56+
message: "New owner created successfully",
57+
profile: {
58+
_id: savedOwner._id,
59+
restaurant_name: savedOwner.restaurant_name,
60+
address: savedOwner.address,
61+
phone: savedOwner.phone,
62+
gstin: savedOwner.gstin,
63+
},
64+
token,
65+
});
2866
} catch (err) {
2967
// Handle errors
3068
console.error(err);
@@ -64,17 +102,7 @@ router.post('/api/auth/login', async (req, res) => {
64102
}
65103

66104
// Prepare the JWT with the owner's fields
67-
const token = jwt.sign(
68-
{
69-
_id: owner._id,
70-
restaurant_name: owner.restaurant_name,
71-
address: owner.address,
72-
phone: owner.phone,
73-
gstin: owner.gstin,
74-
},
75-
JWT_SECRET,
76-
{ expiresIn: '2d' }
77-
);
105+
const token = prepareJWT(owner);
78106

79107
// Send the JWT in a cookie
80108
// res.cookie('jwt', token, {

server/routes/sms.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const { sendOTP, verifyOTP } = require("../services/smsAPI");
55

66
// OTP routes
77
router.post("/apis/sendOTP", (req, res) => {
8+
console.log(req.body);
89
const phone = `+91${req.body.phone}`;
910

1011
if (!phone)
@@ -28,7 +29,6 @@ router.post("/apis/sendOTP", (req, res) => {
2829
message: "Server error, contact administrator",
2930
phone,
3031
success: false,
31-
err,
3232
});
3333
});
3434
});
@@ -38,7 +38,7 @@ router.post("/apis/verifyOTP", (req, res) => {
3838
const phone = `+91${req.body.phone}`;
3939
const code = req.body.code;
4040

41-
if (!phone || code.length != CODE_LENGTH)
41+
if (!phone || !code.length)
4242
return res.status(400).send({
4343
message: "Invalid phone number or code :(",
4444
success: false,

server/services/smsAPI.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ console.log("Twilio params", {
1111
const twilioClient = require('twilio')(TWILIO_ACCOUNT_SID, AUTH_TOKEN);
1212

1313
exports.sendOTP = (phone) => {
14-
console.log("Hello")
1514
return new Promise((resolve, reject) => {
1615
twilioClient.verify.v2.services(SERVICE_ID)
1716
.verifications
@@ -23,7 +22,7 @@ exports.sendOTP = (phone) => {
2322

2423
exports.verifyOTP = (phone, code) => {
2524
return new Promise((resolve, reject) => {
26-
client.verify.v2.services(SERVICE_ID)
25+
twilioClient.verify.v2.services(SERVICE_ID)
2726
.verificationChecks
2827
.create({to: phone, code: code})
2928
.then(resolve)

src/components/otpVerification.jsx

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,38 @@
1+
import axios from 'axios';
12
import React, { useState } from 'react'
23
import { Button } from 'flowbite-react'
34
import OtpInput from 'react-otp-input';
5+
import { toast } from 'react-toastify';
6+
import { SERVER_URL } from '../constants/config';
47

5-
const OTPVerification = () => {
8+
const OTPVerification = (props) => {
69
const [otp, setOtp] = useState('');
710

811
const verifyOTPHandler = () => {
9-
console.log(otp)
12+
console.log("Verify otp:", otp);
13+
// props.postVerification();
14+
15+
axios
16+
.post(`${SERVER_URL}/apis/verifyOTP`, { phone: props.phone, code: otp })
17+
.then((res) => {
18+
if(res.data.success){
19+
toast.success("Verified OTP successfuly !");
20+
props.postVerification();
21+
} else {
22+
toast.error("Invalid OTP !");
23+
}
24+
})
25+
// .catch((err) => {
26+
// console.error(err);
27+
// toast.error("Some error verifying OTP");
28+
// });
1029
}
1130

1231
return (
1332
<div className='flex flex-col mt-[40px]'>
1433
<div>
1534
<span className='text-[20px]'>We have sent you an OTP on</span><br/>
16-
<span className='text-gray-600 dark:text-gray-200 mt-[10px]'>+91 9137357003</span>
35+
<span className='text-gray-600 dark:text-gray-200 mt-[10px]'>+91 {props.phone}</span>
1736
</div>
1837

1938
<div className='flex flex-col justify-center items-center'>

src/constants/config.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
export const SERVER_URL = process.env.NEXT_APP_SERVER_URL || "http://localhost:5000";
1+
export const SERVER_URL = process.env.NEXT_APP_SERVER_URL || "http://localhost:5001";
2+
console.log(process.env);

src/context/AuthContext.jsx

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,50 @@ export const AuthProvider = ({ children }) => {
8989
});
9090
};
9191

92+
const signup = (
93+
restaurant_name,
94+
address,
95+
phone,
96+
gstin,
97+
password,
98+
) => {
99+
setIsProcessingLogin(true);
100+
return new Promise((resolve, reject) => {
101+
// Make an API call to login and get a JWT token
102+
fetch(`${SERVER_URL}/api/auth/signup`, {
103+
method: "POST",
104+
headers: {
105+
"Content-Type": "application/json",
106+
},
107+
body: JSON.stringify({ restaurant_name, address, phone, gstin, password }),
108+
})
109+
.then((res) => res.json())
110+
.then((data) => {
111+
console.log(data);
112+
if (data.success) {
113+
console.log("Signed up !");
114+
localStorage.setItem("token", data.token);
115+
toast.success("Signed up !");
116+
setIsProcessingLogin(false);
117+
setIsLoggedIn(true);
118+
setProfile(data.profile);
119+
resolve(data.profile);
120+
} else {
121+
toast.error("Invalid fields !");
122+
setIsProcessingLogin(false);
123+
setIsLoggedIn(false);
124+
reject(false);
125+
}
126+
})
127+
.catch((error) => {
128+
console.error(error);
129+
toast.error("Some error logging you in !");
130+
setIsProcessingLogin(false);
131+
reject(error);
132+
});
133+
});
134+
}
135+
92136
const logout = () => {
93137
console.log("Logged out !");
94138
localStorage.removeItem("token");
@@ -103,6 +147,7 @@ export const AuthProvider = ({ children }) => {
103147
isProcessingLogin,
104148
profile,
105149
login,
150+
signup,
106151
logout,
107152
}}
108153
>

src/pages/signup.jsx

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,20 @@
11
import OTPVerification from "@/components/otpVerification";
22
import SignupForm from "@/components/signupForm";
3+
import axios from 'axios';
34
import {
5+
useAuth,
46
withAuthenticatedRoute,
57
withoutAuthenticatedRoute,
68
} from "../context/AuthContext";
9+
import { SERVER_URL } from "../constants/config";
10+
import { toast } from "react-toastify";
711

812
const { AppContext } = require("@/context/appContext");
913
const { useContext, useState, useEffect } = require("react");
1014

1115
const Signup = () => {
1216
const appContext = useContext(AppContext);
17+
const { isProcessingLogin, signup } = useAuth();
1318
const [state, setState] = useState(appContext.state);
1419
const [stage, setStage] = useState("createAccount"); // createAccount || otpVerification || verified
1520
const [userInfo, setUserInfo] = useState(null);
@@ -36,15 +41,39 @@ const Signup = () => {
3641
});
3742

3843
setUserInfo({
39-
restuarantName,
40-
restuarantGSTIN,
41-
address,
42-
phoneNumber,
43-
password,
44-
})
45-
setStage("otpVerification");
44+
restuarantName,
45+
restuarantGSTIN,
46+
address,
47+
phoneNumber,
48+
password,
49+
});
50+
51+
axios
52+
.post(`${SERVER_URL}/apis/sendOTP`, { phone: phoneNumber })
53+
.then(() => setStage("otpVerification"))
54+
.catch((err) => {
55+
console.error(err);
56+
toast.error("Some error sending OTP")
57+
});
58+
// setStage("otpVerification");
4659
};
4760

61+
function postVerification() {
62+
console.log("Create DB account with fields", userInfo);
63+
const { restuarantName, restuarantGSTIN, address, phoneNumber, password } =
64+
userInfo;
65+
66+
signup(
67+
restuarantName,
68+
address,
69+
phoneNumber,
70+
restuarantGSTIN,
71+
password
72+
).catch((err) => {
73+
console.log("Err signing up", err);
74+
});
75+
}
76+
4877
return (
4978
<div
5079
className={`w-full min-h-[calc(100vh-60px)] h-auto font-inter flex flex-row ${
@@ -159,7 +188,7 @@ const Signup = () => {
159188
setStage={setStage}
160189
/>
161190
) : (
162-
<OTPVerification />
191+
<OTPVerification phone={userInfo.phoneNumber} postVerification={postVerification} />
163192
)}
164193

165194
{/* {stage == "otpVerification" && <OTPVerification/>} */}

0 commit comments

Comments
 (0)