[go: nahoru, domu]

Skip to content

Commit

Permalink
Added twitch instead of facebook. User premium status improved
Browse files Browse the repository at this point in the history
  • Loading branch information
mohsen-ameli committed Jun 11, 2023
1 parent d5fbfa4 commit 706e2fa
Show file tree
Hide file tree
Showing 19 changed files with 154 additions and 77 deletions.
18 changes: 18 additions & 0 deletions backend/users/migrations/0014_alter_customuser_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.1.4 on 2023-06-11 00:39

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('users', '0013_alter_customuser_id'),
]

operations = [
migrations.AlterField(
model_name='customuser',
name='provider',
field=models.CharField(blank=True, choices=[('credentials', 'credentials'), ('discord', 'discord'), ('google', 'google'), ('twitter', 'twitter')], default='credentials', max_length=11),
),
]
18 changes: 18 additions & 0 deletions backend/users/migrations/0015_alter_customuser_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.1.4 on 2023-06-11 20:49

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('users', '0014_alter_customuser_provider'),
]

operations = [
migrations.AlterField(
model_name='customuser',
name='provider',
field=models.CharField(blank=True, choices=[('credentials', 'credentials'), ('discord', 'discord'), ('google', 'google'), ('twitch', 'twitch')], default='credentials', max_length=11),
),
]
4 changes: 3 additions & 1 deletion backend/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@

PROVIDERS = [
("credentials", "credentials"),
("discord", "discord")
("discord", "discord"),
("google", "google"),
("twitch", "twitch")
]

'''
Expand Down
28 changes: 27 additions & 1 deletion frontend/.vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,33 @@
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"files.exclude": {
"**/.git": false,
"**/.svn": false,
"**/.hg": false,
"**/CVS": false,
"**/.DS_Store": false,
"**/Thumbs.db": false,
".vscode": false,
".next": false,
"node_modules": false,
"tsconfig.json": false,
"yarn.lock": false,
"sandbox.config.json": false,
"README.md": false,
"postcss.config.js": false,
"next-env.d.ts": false,
"LICENSE": false,
".prettierrc": false,
".prettierignore": false,
".gitignore": false,
".eslintrc": false,
".eslintignore": false,
".editorconfig": false,
"tailwind.config.js": false,
"towebp.sh": false,
"next.config.js": false
},
"explorerExclude.backup": {
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
Expand All @@ -39,7 +66,6 @@
"towebp.sh": true,
"next.config.js": true
},
"explorerExclude.backup": {},
"peacock.remoteColor": "#61dafb",
"workbench.colorCustomizations": {
"activityBar.activeBackground": "#93e6fc",
Expand Down
15 changes: 9 additions & 6 deletions frontend/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import NextAuth, { AuthOptions } from "next-auth"
import FacebookProvider from "next-auth/providers/facebook"
import TwitchProvider from "next-auth/providers/twitch"
import DiscordProvider from "next-auth/providers/discord"
import GoogleProvider from "next-auth/providers/google"
import CredentialsProvider from "next-auth/providers/credentials"
Expand All @@ -20,9 +20,9 @@ const discordProvider = DiscordProvider({
},
})

const facebookProvider = FacebookProvider({
clientId: process.env.FACEBOOK_CLIENT_ID!,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET!,
const twitterProvider = TwitchProvider({
clientId: process.env.TWITCH_CLIENT_ID!,
clientSecret: process.env.TWITCH_CLIENT_SECRET!,
})

const googleProvider = GoogleProvider({
Expand Down Expand Up @@ -64,7 +64,7 @@ const credentialsProvider = CredentialsProvider({
})

export const authOptions: AuthOptions = {
providers: [discordProvider, facebookProvider, googleProvider, credentialsProvider],
providers: [discordProvider, twitterProvider, googleProvider, credentialsProvider],
pages: { signIn: "/signin", error: "/signin" },
callbacks: {
async signIn({ user, account }) {
Expand Down Expand Up @@ -103,7 +103,10 @@ export const authOptions: AuthOptions = {

return data.valid
},
async jwt({ token, user, account }) {
async jwt({ token, user, account, trigger, session }) {
if (trigger === "update") {
return { ...token, ...session.user, provider: account?.provider }
}
return { ...token, ...user, provider: account?.provider }
},
async session({ session, token }) {
Expand Down
2 changes: 1 addition & 1 deletion frontend/app/friends/chat/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export default function Chat() {
else validateChat()

const url = `${getServerUrl(false)}/ws/chat/${uuid}/`
setWs(new WebSocket(url))
setWs(() => new WebSocket(url))
}, [session, ws, axiosInstance])

// Web Socket listeners
Expand Down
13 changes: 7 additions & 6 deletions frontend/app/game/[uuid]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import getServerUrl from "@/components/utils/getServerUrl"
import { useGameStore } from "@/game/store/useGameStore"
import { GameDataTypes } from "@/game/types/Game.type"
import switchPlayers from "@/game/utils/SwitchPlayers"
import { useSession } from "next-auth/react"
import { getSession } from "next-auth/react"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"

Expand All @@ -26,7 +26,6 @@ export default function FriendGame({ params }: { params: { uuid: string } }) {
)

const router = useRouter()
const { data: session } = useSession()
const [fetched, setFetched] = useState(false)

// Setting websocket listeners
Expand All @@ -42,7 +41,7 @@ export default function FriendGame({ params }: { params: { uuid: string } }) {

useEffect(() => {
fetchStuff()
}, [session])
}, [])

useEffect(() => {
useGameStore.getState().resetOrbit?.("board", true)
Expand All @@ -58,7 +57,8 @@ export default function FriendGame({ params }: { params: { uuid: string } }) {
}, [])

// Backend has sent game updates
function onMessage(e: MessageEvent) {
async function onMessage(e: MessageEvent) {
const session = await getSession()
const data: GameDataTypes = JSON.parse(e.data)
const id = Number(session?.user.id)

Expand Down Expand Up @@ -194,9 +194,10 @@ export default function FriendGame({ params }: { params: { uuid: string } }) {
}

async function fetchStuff() {
if (!session || fetched) return
if (fetched) return

const axiosInstance = AxiosInstance(session)
const session = await getSession()
const axiosInstance = AxiosInstance(session!)
const { data }: DataType = await axiosInstance.get(`/api/game/valid-match/${params.uuid}/`)

if (!data.valid) {
Expand Down
2 changes: 1 addition & 1 deletion frontend/app/signin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export default function SigninPage() {
<div className="flex justify-between gap-x-4">
<ProviderIcon name="discord" iconOnly={true} />
<ProviderIcon name="google" iconOnly={true} />
<ProviderIcon name="facebook" iconOnly={true} />
<ProviderIcon name="twitch" iconOnly={true} />
</div>
</div>
</>
Expand Down
2 changes: 1 addition & 1 deletion frontend/app/signup/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default function Signup() {
<div className="flex flex-col gap-4 pb-4">
<ProviderIcon name="discord" />
<ProviderIcon name="google" />
<ProviderIcon name="facebook" />
<ProviderIcon name="twitch" />
</div>
</div>
</>
Expand Down
4 changes: 4 additions & 0 deletions frontend/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ const nextConfig = {
protocol: "https",
hostname: "lh3.googleusercontent.com",
},
{
protocol: "https",
hostname: "static-cdn.jtvnw.net",
},
],
},
webpack(config, { isServer }) {
Expand Down
24 changes: 19 additions & 5 deletions frontend/src/components/hooks/useStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import { BaseUser } from "@/types/User.type"
import { useEffect, useRef, useState } from "react"
import notification from "../utils/Notification"
import AxiosInstance from "../utils/AxiosInstance"
import { useSession } from "next-auth/react"
import { getSession, useSession } from "next-auth/react"
import { useRouter } from "next/navigation"
import { useGameStore } from "@/game/store/useGameStore"
import getServerUrl from "../utils/getServerUrl"
import axios from "axios"

type DataType = {
live_game?: string
Expand All @@ -16,9 +17,8 @@ type DataType = {

export default function useStatus() {
const inGame = useGameStore(state => state.inGame)

const router = useRouter()
const { data: session } = useSession()
const { data: session, update } = useSession()
const axiosInstance = AxiosInstance(session!)

const [ws, setWs] = useState<WebSocket | null>(null)
Expand All @@ -27,13 +27,15 @@ export default function useStatus() {
const showReqNotif = useRef(true)
const showRejNotif = useRef(true)

// Starting a websocket connection
useEffect(() => {
if (!session || ws) return

const url = `${getServerUrl(false)}/ws/status/${session.user.id}/`
setWs(() => new WebSocket(url))
}, [session])

// Setting up websocket event listeners
useEffect(() => {
if (!ws || inGame) return

Expand All @@ -49,6 +51,18 @@ export default function useStatus() {
}
}, [ws, inGame])

useEffect(() => {
isUserPremium()
}, [])

// Updating the premium status of the current user
async function isUserPremium() {
const session = await getSession()
if (!session) return
const { data }: { data: boolean } = await axios.get("/api/stripe")
await update({ ...session, user: { ...session?.user, premium: data } })
}

// Accepting a game request
async function accept(id: number) {
const res = await axiosInstance.put("/api/game/handle-match-request/", {
Expand All @@ -64,7 +78,7 @@ export default function useStatus() {
router.push(`/game/${data.game_id}`)
}

// Rejecting the game request
// Rejecting a game request
async function reject(id: number) {
const res = await axiosInstance.put("/api/game/handle-match-request/", {
action: "reject",
Expand All @@ -78,7 +92,7 @@ export default function useStatus() {
showReqNotif.current = true
}

// Handling updates coming from the backend
// Handling incoming updates from the backend
function onMessage(e: MessageEvent) {
const data: DataType = JSON.parse(e.data)

Expand Down
26 changes: 16 additions & 10 deletions frontend/src/components/ui/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,33 @@
import { ButtonHTMLAttributes, useState } from "react"
import { twMerge } from "tailwind-merge"

type InputProps = ButtonHTMLAttributes<HTMLButtonElement>
type InputProps = ButtonHTMLAttributes<HTMLButtonElement> & {
filled?: boolean
}

/**
* A button that has a somewhat cool hover effect
*/
const clickAudio = typeof Audio !== "undefined" ? new Audio("/sounds/button-click.mp3") : null

export default function Button(props: InputProps) {
const { className, onClick, children, disabled, ...rest } = props
const { className, onClick, children, disabled, filled, ...rest } = props

const c = twMerge(
const buttonClassName = twMerge(
`group relative h-10 rounded-lg border-2 border-orange-800 px-4 outline-none ${
disabled && "cursor-not-allowed"
} ${className}`,
)

let bgClassName

if (!filled) {
bgClassName = twMerge(`absolute inset-0 z-10 rounded-md bg-gradient-to-b from-red-500 to-orange-500 opacity-0 transition duration-75 ${disabled ? "" : "group-hover:opacity-100"}`)
} else {
bgClassName = twMerge(`absolute inset-0 z-10 rounded-md bg-gradient-to-b from-red-500 to-orange-500 transition duration-75 ${disabled ? "" : "group-hover:ease-in-out group-hover:from-red-700 group-hover:to-orange-700"}`)
}


const [click] = useState(() => clickAudio)

function handleClick(e: React.MouseEvent<HTMLButtonElement, MouseEvent>) {
Expand All @@ -28,14 +39,9 @@ export default function Button(props: InputProps) {
}

return (
<button type="submit" className={c} onClick={handleClick} {...rest}>
<button type="submit" className={buttonClassName} onClick={handleClick} {...rest}>
<div className="relative z-20">{children}</div>
<div
className={`absolute inset-0 z-10 rounded-md bg-gradient-to-b from-red-500 to-orange-500 opacity-0 transition duration-200 ${
disabled ? "" : "group-hover:opacity-100"
}
`}
></div>
<div className={bgClassName} />
</button>
)
}
Expand Down
11 changes: 5 additions & 6 deletions frontend/src/components/ui/ProviderButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

import toCapitalize from "@/components/utils/ToCapitalize"
import { ProvidersType } from "@/types/User.type"
import { IconProp } from "@fortawesome/fontawesome-svg-core"
import { faFacebook, faGoogle } from "@fortawesome/free-brands-svg-icons"
import { faTwitch, faGoogle } from "@fortawesome/free-brands-svg-icons"
import { faDiscord } from "@fortawesome/free-brands-svg-icons/faDiscord"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { signIn } from "next-auth/react"
Expand All @@ -15,14 +14,14 @@ export default function ProviderIcon({ name, iconOnly = false }: { name: Provide

let className =
"w-full group relative h-10 rounded-lg border-2 px-4 outline-none duration-100 hover:text-white hover:ease-in-out "
let icon = faFacebook
let icon = faTwitch

if (name === "discord") {
className += "border-[#7289da] hover:bg-[#7289da]"
icon = faDiscord
} else if (name === "facebook") {
className += "border-[#3b5998] hover:bg-[#3b5998]"
icon = faFacebook
} else if (name === "twitch") {
className += "border-[#6441a5] hover:bg-[#6441a5]"
icon = faTwitch
} else if (name === "google") {
className += "border-[#4285F4] hover:bg-[#4285F4]"
icon = faGoogle
Expand Down
Loading

1 comment on commit 706e2fa

@vercel
Copy link
@vercel vercel bot commented on 706e2fa Jun 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.