Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: adding user signIn with mail & password functionality #18

Merged
merged 7 commits into from
Apr 14, 2024
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
18 changes: 12 additions & 6 deletions src/app/myticket/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { onAuthStateChanged } from 'firebase/auth'
import { useRouter } from 'next/navigation'
import React, { useContext, useEffect, useState } from 'react'
import '../../styles/globals.css'
import { SubmitButton } from '../../components/shared/SubmitButton'

import { database, auth } from '../../firebase/firebase'
import { Headings, HeadBox } from '../../components/shared/Heading'
Expand Down Expand Up @@ -49,7 +48,7 @@ const MyTicketPage = () => {
const router = useRouter()

const [ticketInfo, setTicketInfo] = useState({
name: '',
name: currentUser?.displayName || '',
teamName: '',
email: '',
bgcolor: '',
Expand All @@ -65,7 +64,7 @@ const MyTicketPage = () => {
}
})
return () => {
unsubscribe() // Unsubscribe from the event when the component unmounts
unsubscribe()
}
}, [currentUser, router])

Expand All @@ -85,6 +84,9 @@ const MyTicketPage = () => {
if (snapshot.exists()) {
const tickets = snapshot.val()
const lastTicketKey = Object.keys(tickets).pop()
const previousTicket = Object.keys(tickets)[Object.keys(tickets).length - 1]
console.log('Last Ticket Key:', lastTicketKey)
console.log('Previous Ticket:', previousTicket)
setTicketInfo({
name: tickets[lastTicketKey].name || currentUser.displayName,
teamName: tickets[lastTicketKey].teamName,
Expand All @@ -110,15 +112,19 @@ const MyTicketPage = () => {
? ref(database, `tickets/${currentUser.uid}/${existingTicketKey}`)
: push(ticketRef)

// Use a promise to wait for the update operation to complete
// promise for the update
const updatePromise = update(updateRef, {
...ticketInfo,
bgcolor: ticketInfo.bgcolor || colors[0],
email: currentUser.email,
gmail: currentUser.email,
googleName: currentUser.displayName,
ticketId: existingTicketKey ? ticketInfo.ticketId : ticketInfo.ticketId + 1
})
updatePromise.then(() => {
const newTicketKey = existingTicketKey || updateRef.key
setShowModal(true)
console.log('Ticket generated successfully', ticketInfo)
console.log('with ID', newTicketKey, 'for User', currentUser.uid)
})
}
}
Expand All @@ -138,7 +144,7 @@ const MyTicketPage = () => {
<Input
type="text"
name="name"
placeholder="Name"
placeholder={ticketInfo.name ? ticketInfo.name : 'Name'}
value={ticketInfo.name}
onChange={handleChange}
/>
Expand Down
45 changes: 34 additions & 11 deletions src/components/SignUp.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,19 @@ import {
ButtonBox,
ToggleButton,
Btn,
Login,
Register,
CardsA,
CardsB,
CardImage
CardImage,
InputGroup
} from './signup.styles'

import { AuthLogoLinks } from '../config/AuthProviders'

import {
signUpWithEmailAndPassword,
signUpWithGitHub,
signUpWithGoogle
signUpWithGoogle,
signInWithEmailAndPass
} from '../firebase/signupAuth'

const SignUp = () => {
Expand All @@ -43,10 +43,29 @@ const SignUp = () => {

const handleSignUp = async () => {
try {
await signUpWithEmailAndPassword(email, password, name)
router.push('/myticket')
const user = await signUpWithEmailAndPassword(email, password, name)
if (user) {
router.push('/myticket')
}
} catch (error) {
console.error('Signup error:', error.message)
if (error.code === 'auth/invalid-email') {
document.getElementById('signup-email').style.border = '1px solid red'
} else if (error.code === 'auth/weak-password') {
document.getElementById('signup-password').style.border = '1px solid yellow'
}
}
}
const handleSignIn = async () => {
try {
const user = await signInWithEmailAndPass(email, password)
if (user) {
router.push('/myticket')
}
} catch (error) {
console.error('Signin error:', error.message)
document.getElementById('signin-password').style.border = '1px solid red'
document.getElementById('signin-email').style.border = '1px solid red'
}
}
const handleGoogleSignup = async () => {
Expand Down Expand Up @@ -111,7 +130,7 @@ const SignUp = () => {
<ToggleButton onClick={switchToRegister}>Sign In</ToggleButton>
</ButtonBox>

<Login loginFormLeft={loginFormLeft}>
<InputGroup style={{ left: loginFormLeft }}>
<AuthButton type="submit" onClick={handleGoogleSignup}>
<AuthLogoImg src={AuthLogoLinks[0].url} alt="Google" />
Sign up with Google
Expand All @@ -131,22 +150,24 @@ const SignUp = () => {
/>
<FormText>Email:</FormText>
<Input
id="signup-email"
type="email"
placeholder="Enter your email"
value={email}
onChange={handleEmailChange}
/>
<FormText>Password:</FormText>
<Input
id="signup-password"
type="password"
placeholder="Enter your password"
value={password}
onChange={handlePasswordChange}
/>
<SubmitButton onClick={handleSignUp}>Sign up</SubmitButton>
</Login>
</InputGroup>

<Register registerFormLeft={registerFormLeft}>
<InputGroup style={{ left: registerFormLeft }}>
<AuthButton type="submit" onClick={handleGoogleSignup}>
<AuthLogoImg src={AuthLogoLinks[0].url} alt="Google" />
Sign in with Google
Expand All @@ -159,20 +180,22 @@ const SignUp = () => {
<CenterText>Or</CenterText>
<FormText>Email:</FormText>
<Input
id="signin-email"
type="email"
placeholder="Enter your email"
value={email}
onChange={handleEmailChange}
/>
<FormText>Password:</FormText>
<Input
id="signin-password"
type="password"
placeholder="Enter your password"
value={password}
onChange={handlePasswordChange}
/>
<SubmitButton onClick={handleSignUp}>Sign in</SubmitButton>
</Register>
<SubmitButton onClick={handleSignIn}>Sign in</SubmitButton>
</InputGroup>
</FormBox>
</Hero>
)
Expand Down
2 changes: 1 addition & 1 deletion src/components/shared/GlobalButton.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react'
import styled from 'styled-components'

const ButtonCont = styled.button`
const ButtonCont = styled.span`
height: 52px;
cursor: pointer;
border: none;
Expand Down
2 changes: 1 addition & 1 deletion src/context/AuthContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const AuthProvider = ({ children }) => {

useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
console.log('Auth State Changed:', user)
//console.log('Auth State Changed:', user)
setCurrentUser(user)
})

Expand Down
5 changes: 0 additions & 5 deletions src/firebase/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getDatabase } from 'firebase/database'

//import firebaseConfig2 from '../../.env'
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
Expand All @@ -17,10 +16,6 @@ const firebaseConfig = {
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
}

//console.log('Firebase Config:', firebaseConfig)
// Initialize Firebase
const app = initializeApp(firebaseConfig)
export const auth = getAuth(app)
export const database = getDatabase(app)
//export const database = firebase.database();
//export const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
20 changes: 14 additions & 6 deletions src/firebase/signupAuth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
GithubAuthProvider,
GoogleAuthProvider,
signInWithPopup
Expand All @@ -16,33 +17,42 @@ export const signUpWithEmailAndPassword = async (email, password, name) => {

// adding name to db
const userRef = ref(database, `users/${user.uid}`)
console.log('adding name to db', user.uid)
await set(userRef, {
name: name,
email: user.email
})

return user
} catch (error) {
//console.error('Error signing up:', error.message)
throw error
}
}

export const signInWithEmailAndPass = async (email, password) => {
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password)
const user = userCredential.user

return user
} catch (error) {
throw error
}
}

// signup with google function
export const signUpWithGoogle = async () => {
try {
// Configure Google provider
const provider = new GoogleAuthProvider()

// Sign in with Google
const userCredential = await signInWithPopup(auth, provider)
const user = userCredential.user

// Check if user already exists in the database
const userRef = ref(database, `users/${user.uid}`)
const snapshot = await get(userRef)

// If user doesn't exist, add them to the database
// adding user to db in users/
if (!snapshot.exists()) {
await set(userRef, {
name: user.displayName,
Expand All @@ -63,10 +73,8 @@ export const signUpWithGitHub = async () => {

try {
await signInWithPopup(auth, provider)
// Handle the successful sign-up
//console.log('User signed up with GitHub:', result.user)
} catch (error) {
// Handle errors
//console.error('Error signing up with GitHub:', error.message)
}
}
Loading