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

Angus Townsley #132

Open
wants to merge 13 commits into
base: freedom
Choose a base branch
from
Open
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
4 changes: 0 additions & 4 deletions .env.example

This file was deleted.

1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ dist-ssr

# Editor directories and files
.vscode/*
.next
!.vscode/extensions.json
.idea
.DS_Store
Expand Down
57 changes: 57 additions & 0 deletions app/api/movies/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { NextRequest, NextResponse } from 'next/server'
import { hasValidToken, isAdmin } from '../../../lib/authFunctions'
import { createMovie, getMovies, getUserInfo } from '../../../lib/data'
import { UserInfo } from '../../../lib/definitions'

export async function POST(req: NextRequest) {
try {
const { title, description, runtimeMins } = await req.json()

const parseMins = Number(runtimeMins)

if (!title || !description || !runtimeMins || isNaN(parseMins)) {
return NextResponse.json(
{ error: 'Fields missing in the request body' },
{ status: 400 }
)
}
const token = req.headers.get('authorization').split(' ')[1]
const tokenData = hasValidToken(token)

if (!tokenData || isNaN(Number(tokenData.sub))) {
return NextResponse.json(
{ error: 'Invalid Credentials: Bad Token' },
{ status: 401 }
)
}

const userInfo: UserInfo = await getUserInfo(Number(tokenData.sub))

if (!isAdmin(userInfo)) {
return NextResponse.json(
{ error: 'Creation Failed, No Permission' },
{ status: 403 }
)
}

const newMovie = await createMovie({
title,
description,
runtimeMins: parseMins,
})

return NextResponse.json({ movie: newMovie }, { status: 201 })
} catch (e) {
return NextResponse.json({ error: e.message }, { status: 500 })
}
}

export async function GET(req: NextRequest) {
try {
const movies = await getMovies()

return NextResponse.json({ movies }, { status: 200 })
} catch (e) {
return NextResponse.json({ error: e.message }, { status: 500 })
}
}
19 changes: 19 additions & 0 deletions app/api/users/controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { NextApiRequest, NextApiResponse } from 'next'
import * as data from '../../../lib/data'

export async function registerUser(req: NextApiRequest, res: NextApiResponse) {
try {
const { username, password } = req.body
if (!username || !password) {
return res
.status(400)
.send({ error: 'Requirements missing in the request body' })
}
const newUser = await data.registerUser({ username, password })

return res.status(201).send({ user: newUser })
} catch (e) {
console.log(e.message)
return res.status(500).send({ error: e.message })
}
}
39 changes: 39 additions & 0 deletions app/api/users/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server'
import { getUserInfo } from '../../../../lib/data'
import * as bcrypt from 'bcrypt'
import * as jwt from 'jsonwebtoken'

export async function POST(req: NextRequest) {
const secret = process.env['SECRET_STRING']

try {
const { username, password } = await req.json()

if (!username || !password) {
return NextResponse.json(
{ error: 'Fields missing in the request body' },
{ status: 400 }
)
}

const userData = await getUserInfo(username)

const verify = await bcrypt.compare(password, userData.passwordHash)

if (!verify) {
return NextResponse.json(
{ error: 'Incorrect Credentials' },
{ status: 401 }
)
}

const token = jwt.sign({ sub: userData.id }, secret)

return NextResponse.json({ token }, { status: 200 })
} catch (e: any) {
if (e.code === 'P2025') {
return NextResponse.json({ error: e.message }, { status: 404 })
}
return NextResponse.json({ error: e.message }, { status: 500 })
}
}
26 changes: 26 additions & 0 deletions app/api/users/register/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextRequest, NextResponse } from 'next/server'
import { registerUser } from '../../../../lib/data'
import { error } from 'console'

export async function POST(req: NextRequest) {
try {
const { username, password } = await req.json()

if (!username || !password) {
return NextResponse.json(
{ error: 'Fields missing in the request body' },
{ status: 400 }
)
}

const newUser = await registerUser({ username, password })
return NextResponse.json({ user: newUser }, { status: 201 })
} catch (e: any) {
if (e.message === 'Username already in use') {
return NextResponse.json({ error: e.message }, { status: 409 })
}

console.error(e.message)
return NextResponse.json({ error: e.message }, { status: 500 })
}
}
14 changes: 14 additions & 0 deletions app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

nav{
display: flex;
gap:20px
}

form{
display: flex;
flex-direction: column;
align-items: center;
}
13 changes: 13 additions & 0 deletions app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import './globals.css'

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
42 changes: 42 additions & 0 deletions app/login/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use client'

import { useState, useEffect } from 'react'
import Form from '../../components/form/Form'
import { useRouter } from 'next/navigation'
import Navbar from '../../components/navigation/navbar'

export default function page() {
const router = useRouter()

const [token, setToken] = useState('')

useEffect(() => {
const getToken = localStorage.getItem('token')
setToken(getToken || null)
}, [])

useEffect(() => {
if (token === null) {
router.push('/')
}
}, [])

return (
<>
<Navbar token={token} setToken={setToken} />
<section className="py-24 md:py-32 bg-white">
<div className="container px-4 mx-auto">
<div className="mb-6 text-center">
<h3 className="mb-4 text-2xl md:text-3xl font-bold">
Sign in to your account
</h3>
<p className="text-lg text-coolGray-500 font-medium">
Gosh, I hope this works
</p>
</div>
<Form type="login" />
</div>
</section>
</>
)
}
19 changes: 19 additions & 0 deletions app/movies/MovieForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Form from '../../components/form/Form'

export default function MovieForm(token) {
return (
<section className="py-24 md:py-32 bg-white">
<div className="container px-4 mx-auto">
<div className="mb-6 text-center">
<h3 className="mb-4 text-2xl md:text-3xl font-bold">
Add a new Moive!
</h3>
<p className="text-lg text-coolGray-500 font-medium">
Make sure it's a good one!
</p>
</div>
<Form type="movie" token={token} />
</div>
</section>
)
}
59 changes: 59 additions & 0 deletions app/movies/Movies.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import useSWR from 'swr'

export default function Movies() {
const fetcher = (...args) =>
fetch('/api/movies', {
method: 'GET',
headers: { 'Content-type': 'application/json' },
}).then((res) => res.json())

const { data, error, isLoading } = useSWR('/api/movies', fetcher)

if (isLoading) {
return (
<div>
<h1>Movies</h1>
<p>loading...</p>
</div>
)
}

if (error) {
return <div>{error.message}</div>
}

function pluralise(runtimeMins: number) {
if (runtimeMins > 1) {
return 's'
}

return ''
}
return (
<section className="py-24 md:pt-32 bg-white">
<div className="container px-4 mx-auto">
<h1 className="mb-4 text-4xl md:text-5xl leading-tight text-coolGray-900 font-bold tracking-tighter">
Movies
</h1>
<ul>
{data.movies.map((element) => {
return (
<li className="group relative h-full px-8 pt-16 pb-8 bg-coolGray-50 group-hover:bg-white rounded-md shadow-md hover:shadow-xl transition duration-200">
<h3 className="mb-4 text-xl leading-7 text-coolGray-900 font-bold max-w-xs">
Title:{element.title}
</h3>
<p className="text-coolGray-500 group-hover:text-coolGray-600 font-medium transition duration-200">
{element.description}
</p>
<p className="text-coolGray-500 group-hover:text-coolGray-600 font-medium transition duration-200">
Runtime: {`${element.runtimeMins} minute`}
{pluralise(element.runtimeMins)}
</p>
</li>
)
})}
</ul>
</div>
</section>
)
}
29 changes: 29 additions & 0 deletions app/movies/create/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use client'

import { useState, useEffect } from 'react'
import Navbar from '../../../components/navigation/navbar'
import { useRouter } from 'next/navigation'
import MovieForm from '../MovieForm'

export default function page() {
const router = useRouter()
const [token, setToken] = useState('')

useEffect(() => {
const getToken = localStorage.getItem('token')
setToken(getToken || null)
}, [])

useEffect(() => {
if (token === null) {
router.push('/login')
}
}, [token])

return (
<>
<Navbar token={token} setToken={setToken} />
<MovieForm token={token} />
</>
)
}
30 changes: 30 additions & 0 deletions app/movies/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use client'
import { useRouter } from 'next/navigation'
import { useState, useEffect } from 'react'
import Navbar from '../../components/navigation/navbar'
import Movies from './Movies'
import MovieForm from './MovieForm'

export default function page() {
const router = useRouter()
const [token, setToken] = useState('')

useEffect(() => {
const getToken = localStorage.getItem('token')
setToken(getToken || null)
}, [])

useEffect(() => {
if (token === null) {
router.push('/login')
}
}, [token])

return (
<>
<Navbar token={token} setToken={setToken} />
<Movies />
<MovieForm token={token}/>
</>
)
}
Loading