//tips
//smart contract
一部のURL直叩きによるページ移動を制限する方法を考える。
Next.jsで全ページで特定の処理をはさむためには、Appコンポーネント(_app.tsx)にその処理を書く必要があるのだが、今回は[id]以降の部分に認証確認をつけたい。
この認証確認の元となるauthの情報を<AuthProvider>に保持させるのが一般的なよう。これはグローバルに保存しているのと変わらないか。
<AuthProvider>
<Component {...pageProps} />
</AuthProvider>
https://colinhacks.com/essays/nextjs-firebase-authentication
https://betterprogramming.pub/implement-user-authentication-with-next-js-and-firebase-fb9414adba08
まずはlocalastorageにauth情報を保存して、url直叩きされてもuseeffectで参照・制御できるようにする。cookieを使用する方法も見つけたのでどちらがいいか調べてみたら、今回はlocalstorageの方が何度も認証作業をしないので使い勝手が良さそう。
https://qiita.com/terufumi1122/items/76bafb9eed7cfc77b798
https://call.omnidatabank.jp/blog/localstorage/#:~:text=%E3%81%97%E3%81%8B%E3%81%97%E3%83%AD%E3%83%BC%E3%82%AB%E3%83%AB%E3%82%B9%E3%83%88%E3%83%AC%E3%83%BC%E3%82%B8%E3%81%A8Cookie,%E3%81%AF4%20KB%E3%81%97%E3%81%8B%E3%81%82%E3%82%8A%E3%81%BE%E3%81%9B%E3%82%93%E3%80%82
Localstorageにauth情報を保存するために登録を行なった時点またはログインをした時点でlocalstorageに情報を格納させる仕組みを作る。
const [authhistory, setauthHistory] = useState();
をまずは作成。
localStorage.setItem('キー', ‘値’);のようなので、
signInWithEmailAndPassword(auth,email,password)
.then((cred)=>{
localStorage.setItem('authhistory',email)
一旦ログアウトして再度ログインした上で、localStorage.setItem('authhistory',email)を発動させ、その後にeditに移動し、下記が機能しているかを確認する。
const authhistory=localStorage.getItem(authhistory);
console.log('authhistory')
console.log(authhistory)
すると、
localStorage is not definedのエラーがeditの読み込み時に発生。
そう、localStorage オブジェクトは、クライアントサイド JS でしか参照できないため、Next.js などのサーバーサイドレンダリング時に値を参照しようとするとエラーになる。
なので参照タイミングをうまく制御しながら、連動させていくことになる
useeffectを多少加工。
まず先に実際にlocalStorageで値を取得できるのかを[id]のみで試してから移る。
async function handleOnAuthIn(e) {
e.preventDefault();
console.log('aiu')
const email=umail
const password=upass
signInWithEmailAndPassword(auth,email,password)
.then((cred)=>{
//console.log('user loged in:',cred.user)
localStorage.setItem('authhistory',email)
setUmail('')
setUpass('')
}).then(()=>{
console.log('localStorage.getItem(authhistory)')
console.log(localStorage.getItem(authhistory))
})
きちんと引数をテキストにしたらconsole.log(localStorage.getItem('authhistory’))反映された。機能している。
次は遷移先での確認。
useEffect(() => {
setauthHistory(localStorage.getItem('authhistory'))
if (authhistory !== defaultValue) {
console.log('authhistory')
console.log(authhistory)
}
}, [authhistory])
authhistoryが変更されたタイミングで更新をストップさせる。
こちらできちんとlocalStorageにて値の引き渡しができた。
なので、このlocalstrageの値とninja[0].mailのものを比較すれば良いか。
下記もきちんと確認できた。
console.log('ninja[0].mail')
console.log(ninja[0].mail)
これで意図したように機能した。
useEffect(() => {
console.log('aaa')
setauthHistory(localStorage.getItem('authhistory'))
if (authhistory) {
console.log('authhistory')
console.log(authhistory)
console.log('ninja[0].mail')
console.log(ninja[0].mail)
if(authhistory!=ninja[0].mail){router.push('/ID/'+ninja[0].userid)}
}
}, [authhistory])
参考:
https://maku.blog/p/cwdyhec/