This commit is contained in:
cupcakearmy
2019-05-22 20:34:58 +02:00
parent 7b81984ce7
commit dcbc4bcdd7
73 changed files with 4138 additions and 0 deletions

29
www/utils/api.js Normal file
View File

@@ -0,0 +1,29 @@
import nextCookie from 'next-cookies'
import axios from 'axios'
import cookie from 'js-cookie'
import Router from 'next/dist/lib/router'
export const callAPI = async (ctxOrNull, { url, method, data }) => {
// Whether ctx is set or not
const token = ctxOrNull
? nextCookie(ctxOrNull).token
: cookie.get('token')
const redirect = () => process.browser
? Router.push('/login')
: ctxOrNull.res.writeHead(302, { Location: '/login' }).end()
const response = await axios({
method: method || 'get',
url,
headers: {
'Authorization': `Bearer ${token}`,
},
data,
})
if (response.status === 401) redirect()
else return response.data.body
}

67
www/utils/auth.js Executable file
View File

@@ -0,0 +1,67 @@
import React from 'react'
import Router from 'next/router'
import nextCookie from 'next-cookies'
import cookie from 'js-cookie'
import { useLocalStorageWatcher } from './hooks'
export const login = ({ token }) => {
cookie.set('token', token)
Router.push('/me')
}
export const logout = () => {
cookie.remove('token')
// to support logging out from all windows
window.localStorage.setItem('logout', Date.now().toString())
Router.push('/login')
}
const syncLogout = (event) => {
if (event.key !== 'logout') return
window.localStorage.removeItem('logout')
Router.push('/login')
}
export const withAuthSync = Wrapped => {
const wrapper = (props) => {
useLocalStorageWatcher(syncLogout)
return <Wrapped {...props}/>
}
wrapper.getInitialProps = async (ctx) => {
const token = auth(ctx)
const componentProps = Wrapped.getInitialProps && await Wrapped.getInitialProps(ctx)
return { ...componentProps, token }
}
return wrapper
}
export const auth = ctx => {
const { token } = nextCookie(ctx)
/*
* This happens on server only, ctx.req is available means it's being
* rendered on server. If we are on server and token is not available,
* means user is not logged in.
*/
if (ctx.req && !token) {
ctx.res.writeHead(302, { Location: '/login' })
ctx.res.end()
return
}
// We already checked for server. This should only happen on client.
if (!token) {
Router.push('/login')
}
return token
}

12
www/utils/hooks.js Normal file
View File

@@ -0,0 +1,12 @@
import React, { useEffect } from 'react'
export const useLocalStorageWatcher = (fn) => {
useEffect(() => {
window.addEventListener('storage', fn)
return () => {
window.removeEventListener('storage', fn)
}
}, [])
}

9
www/utils/misc.js Normal file
View File

@@ -0,0 +1,9 @@
export const capitalize = s => s[0].toUpperCase() + s.slice(1)
const getRandomItemFromArray = a => a[Math.floor((Math.random() * a.length))]
export const getRandomSlogan = () => '💸 ' + getRandomItemFromArray(
['centkrieger', 'pfandsklave', 'minusexperte'],
)
export const getAvatarOfFallback = avatar => avatar || '_fallback'