Skip to content

Commit

Permalink
needed files for demo
Browse files Browse the repository at this point in the history
  • Loading branch information
CrazEpic committed May 6, 2024
1 parent 8e0c36f commit c4afcdc
Show file tree
Hide file tree
Showing 19 changed files with 269 additions and 49 deletions.
19 changes: 19 additions & 0 deletions cert-dev.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDHTCCAgWgAwIBAgIJMSxRVGwPXrarMA0GCSqGSIb3DQEBCwUAMCwxKjAoBgNV
BAMTIWRldi11NGptbThnaTYxeXJ6eXJrLnVzLmF1dGgwLmNvbTAeFw0yNDA0MTYx
NjQ0MDBaFw0zNzEyMjQxNjQ0MDBaMCwxKjAoBgNVBAMTIWRldi11NGptbThnaTYx
eXJ6eXJrLnVzLmF1dGgwLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAM9Jg2WQCaB1da7jd6h2HhSB1Ujz7pP//0bnzzvXRJe2jXC0K78WWZMx56Je
mDbt02e9jr/AYP/IdPZ6alxQhzRu3LQSe+CKmrNyKQ3qVsHO0LpfpT62F28iyR1+
9StOv5p6du80WLRuOLOLf52bnfvOZtKiGMkSmQIFks7rlf6+5kttIvC+rC7EEzjX
c8HaHO/hhVQzYbZDXFpee6brMscoqwOGfRB1jfYrn6Qnwn7CTiS4IgNiZwsMfvbu
K7DBpNTipMOPYMK3kQ3J9tQaLBu2qtdVq8y8+2mZn2anOr+9Ge9eLCR367vZVP9M
HniCfKD+MJrEK/4u8P9Bj+90PHMCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAd
BgNVHQ4EFgQUcppxfd/gtygwJpRxZCq8uD7R0UcwDgYDVR0PAQH/BAQDAgKEMA0G
CSqGSIb3DQEBCwUAA4IBAQBJrHzC8FXvJKJ/zweygVQdFsVds68ysclP2jDf2Dcr
wIDomsj0EsaFBoY60xxsf8Te3AU9wgt+1CLARhm34ilSnCmsXNYphcosm6vlMZd/
WHmU2Zm3tNO3l/soq0VAPaZrYij3JmQe1ag8Ei4RCoQuL2/5CeBZrmOMrmlyMaSZ
rFW0ZGXBMNtwyyHYsKA+ygXj6Sh86TQSnjTzBxopTSp5gO+onddP7GHtB9Pf9mpg
LplnjMsshkxPYzW0Ki3nfNPPJrlNDDBbEgJKlHklItZcUmZvyVics2jVA7s769nM
QTDcmkX2s8+k7aSH033twUJKpzFLCIam0eK689JyVKFC
-----END CERTIFICATE-----
13 changes: 4 additions & 9 deletions components/LogInSignUp.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,15 @@
<div class="">
<button
class="hover:text-gray-300 transition font-semibold duration-400 text-white font-bold py-2 px-5 rounded-lg"
style="background-color:#154734" @click="openLogIn">Log In</button>
style="background-color:#154734" @click="login"> {{ "Log In" }}</button>
</div>
</div>
<SignUpOverlay v-if="showSignUp" @closeSignUpOverlay="closeSignUp"></SignUpOverlay>
<LogInOverlay v-if="showLogIn" @closeLogInOverlay="closeLogIn"></LogInOverlay>
</template>

<script setup lang="ts">
const showSignUp = ref(false)
const showLogIn = ref(false)
const openSignUp = () => { showSignUp.value = true }
const closeSignUp = () => { showSignUp.value = false }
const openLogIn = () => { showLogIn.value = true }
const closeLogIn = () => { showLogIn.value = false }
const login = async () => {
window.location.href='api/login'
}
</script>

<style></style>
15 changes: 15 additions & 0 deletions components/LogOut.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<template>
<div class="flex md:flex md:flex-grow flex-row-reverse space-x-3 mt-5 mr-4 mb-2">
<div class="">
<button
class="hover:text-gray-300 transition font-semibold duration-400 text-white font-bold py-2 px-5 rounded-lg"
style="background-color:#FF0000" @click="logout"> {{ "Log Out" }}</button>
</div>
</div>
</template>

<script setup lang="ts">
const logout = async () => {
window.location.href='api/logout'
}
</script>
6 changes: 4 additions & 2 deletions components/TopRightNavbar.vue
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
<template>
<div class="">
<Profile v-if="userTrue"></Profile>
{{ sruser }}
<Profile v-if="sruser"></Profile>
<LogOut v-if="sruser"></LogOut>
<LogInSignUp v-else></LogInSignUp>
</div>
</template>

<script setup lang="ts">
const userTrue = ref(false)
const sruser = useCookie("sruser")
</script>


Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"bootgame": "tsx server/Game_Manager/src/index.ts",
"bootcontrol": "tsx server/Controller/src/index.ts"
"bootcontrol": "tsx server/Controller/src/index.ts",
"bootrasp": "tsx server/Raspberry/src/index.ts"
},
"dependencies": {
"@prisma/client": "^5.11.0",
Expand Down
30 changes: 0 additions & 30 deletions prisma/migrations/20240312205118_init/migration.sql

This file was deleted.

3 changes: 0 additions & 3 deletions prisma/migrations/migration_lock.toml

This file was deleted.

8 changes: 4 additions & 4 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ generator client {
}

model Player {
id Int @id @default(autoincrement())
user_id String @id
username String @unique
email String @unique
name String?
Expand All @@ -24,10 +24,10 @@ model Match {
}

model PlayersInMatches {
player Player @relation(fields: [playerID], references: [id])
playerID Int
player Player @relation(fields: [playerID], references: [user_id])
playerID String
playerScore Int
match Match @relation(fields: [matchID], references: [id])
matchID Int
@@id([playerID, matchID])
}
}
Binary file removed prisma/test.db
Binary file not shown.
Binary file removed prisma/test.db-journal
Binary file not shown.
12 changes: 12 additions & 0 deletions server/Raspberry/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "Raspberry",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
93 changes: 93 additions & 0 deletions server/Raspberry/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { WebSocketServer } from "ws"
import dotenv from "dotenv"

// Environment variables
dotenv.config({ path: "./.env" })
const PORT_GM_RASPBERRY: number = parseInt(`${process.env.PORT_GM_RASPBERRY}`)
const PORT_WSS_CONTROLLER_RASPBERRY: number = parseInt(`${process.env.PORT_WSS_CONTROLLER_RASPBERRY}`)

// Shared variables
let ready: boolean = true
let timer: number = 0
let score1: number = 0
let score2: number = 0

// FOR GAME MANAGER
const wss_gm = new WebSocketServer({ port: PORT_GM_RASPBERRY})

wss_gm.on("listening", () => {
console.log(`WebSocket wss_gm is running on ws://localhost:${PORT_GM_RASPBERRY}`)
})

wss_gm.on("error", (error) => {
console.log("WebSocket wss_gm error: " + error)
})

wss_gm.on("close", () => {
console.log("WebSocket wss_gm closed")
})

wss_gm.on("connection", (ws: any, request) => {
ws.on("message", (data: any) => {
const { type, payload } = JSON.parse(data)
if(type === "CHECK_READY"){ // should already be in
console.log(`Telling GM: ready is ${ready}`)
ws.send(JSON.stringify({
"type": "IS_READY",
"payload": ready
}))
}
else if(type === "GAME_START"){
timer = payload["timer"]
const broadcastTimer = setInterval(() => {
if(timer === 0){
clearInterval(broadcastTimer)
clearInterval(broadcastScore)
ws.send(JSON.stringify({
"type": "GAME_END",
"payload": {"timer": timer, "score1": score1, "score2": score2}
}))
}
else{
ws.send(JSON.stringify({
"type": "TIMER_UPDATE",
"payload": {"timer": timer}
}))
timer--
}
}, 1000)
const broadcastScore = setInterval(() => {
ws.send(JSON.stringify({
"type": "SCORE_UPDATE",
"payload": {"score1": score1, "score2": score2}
}))
}, 1000)
}
})
})

// FOR CONTROLLER
const wss_control = new WebSocketServer({ port: PORT_WSS_CONTROLLER_RASPBERRY})

wss_control.on("listening", () => {
console.log(`WebSocket wss_control is running on ws://localhost:${PORT_WSS_CONTROLLER_RASPBERRY}`)
})

wss_control.on("error", (error) => {
console.log("WebSocket wss_control error: " + error)
})

wss_control.on("close", () => {
console.log("WebSocket wss_control closed")
})

wss_control.on("connection", (ws: any, request) => {
ws.on("message", (data: any) => {
const { type, payload } = JSON.parse(data)

if(type === "KEY_INPUT"){ // should already be in
const { keys, playernumber }: {keys: string, playernumber: number} = payload
console.log(`Player ${playernumber} pressed ${keys}`)
}
})
})
13 changes: 13 additions & 0 deletions server/Raspberry/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
17 changes: 17 additions & 0 deletions server/api/auth0.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import {nanoid} from "nanoid"

const state: {[key: string]: number} = {};
const genState = () => { const s = nanoid(); state[s] = 1; return s}
const runtime = useRuntimeConfig()

export const loginRedirectUrl = () => `${runtime.ISSUER}authorize?response_type=id_token&response_mode=form_post&client_id=${runtime.AUTH0_CLIENTID}&scope=openid%20email&redirect_uri=${encodeURIComponent(runtime.BASEURL!+"api/callback")}&nonce=${genState()}`
export const logoutRedirectUrl = (id_token: string) => `${runtime.ISSUER}oidc/logout?id_token_hint=${id_token}&post_logout_redirect_uri=${encodeURIComponent(runtime.BASEURL!+"api/logoutcallback")}&nonce=${genState()}`

// Number used once
export const verifyNonce = (nonce: string) => {
if (state[nonce]) {
delete state[nonce]
return true
}
return false
}
37 changes: 37 additions & 0 deletions server/api/callback.post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import jwt from "jsonwebtoken"
import fs from "fs"
import { verifyNonce } from "./auth0"
import { PrismaClient } from "@prisma/client"
import { nanoid } from "nanoid"

const prisma = new PrismaClient()

export default defineEventHandler(async event => {
const body = await readBody(event)
const srtoken = body.id_token
const claims: any = jwt.verify(srtoken, fs.readFileSync(process.cwd()+"/cert-dev.pem"))
// check for valid nonce claim
if(claims instanceof Object && "nonce" in claims && verifyNonce(claims["nonce"].toString())){
const user_id: string = claims["sub"]
const email: string = claims["email"]
const find_user = await prisma.player.findUnique({
where: {
user_id: user_id
}
})
// if not in database yet, create new player in database
let username: string
if(find_user){
username = find_user.username
}
else{
username = nanoid()
const user = await prisma.player.create({
data: { user_id: user_id, username: username, email: email},
})
}
setCookie(event, "srtoken", srtoken)
setCookie(event, "sruser", username)
}
await sendRedirect(event, "/")
})
5 changes: 5 additions & 0 deletions server/api/login.get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { loginRedirectUrl } from "./auth0"

export default defineEventHandler(async event => {
await sendRedirect(event, loginRedirectUrl() || "")
})
6 changes: 6 additions & 0 deletions server/api/logout.get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { logoutRedirectUrl } from "./auth0"

export default defineEventHandler(async event => {
const id_token = getCookie(event, "srtoken")
await sendRedirect(event, logoutRedirectUrl(id_token as string) || "")
})
5 changes: 5 additions & 0 deletions server/api/logoutcallback.get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default defineEventHandler(async event => {
setCookie(event, "srtoken", "")
setCookie(event, "sruser", "")
await sendRedirect(event, "/")
})
33 changes: 33 additions & 0 deletions server/middleware/auth0.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {loginRedirectUrl, logoutRedirectUrl} from "../api/auth0"
import jwt from "jsonwebtoken"
import fs from "fs"
const runtime = useRuntimeConfig()

import { PrismaClient } from "@prisma/client"
const client = new PrismaClient()

const publicURLs = []

export default defineEventHandler(async event => {
const srtoken = getCookie(event, "srtoken") || ""

if(srtoken){

}

// if (!srtoken) {
// await sendRedirect(event, loginRedirectUrl());
// }
// else {
// // theoretically logged in
// if (srtoken) {
// try {
// const claims = jwt.verify(srtoken, fs.readFileSync(process.cwd()+"/cert-dev.pem"))
// } catch(e){
// console.error(e)
// setCookie(event,"srtoken","")
// setCookie(event,"sruser","")
// }
// }
// }
})

0 comments on commit c4afcdc

Please sign in to comment.