snort/src/pages/Login.js

81 lines
2.4 KiB
JavaScript
Raw Normal View History

2022-12-27 23:46:13 +00:00
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
2022-12-29 22:23:41 +00:00
import { useNavigate } from "react-router-dom";
2022-12-27 23:46:13 +00:00
import * as secp from '@noble/secp256k1';
import { bech32 } from "bech32";
2022-12-29 22:23:41 +00:00
import { setPrivateKey, setNip07PubKey } from "../state/Login";
2022-12-27 23:46:13 +00:00
2022-12-18 14:51:47 +00:00
export default function LoginPage() {
2022-12-27 23:46:13 +00:00
const dispatch = useDispatch();
const navigate = useNavigate();
2022-12-29 10:51:32 +00:00
const publicKey = useSelector(s => s.login.publicKey);
2022-12-27 23:46:13 +00:00
const [key, setKey] = useState("");
2023-01-01 19:57:27 +00:00
useEffect(() => {
if (publicKey) {
navigate("/");
}
}, [publicKey]);
2022-12-27 23:46:13 +00:00
function doLogin() {
2022-12-29 10:51:32 +00:00
if (key.startsWith("nsec")) {
2022-12-27 23:46:13 +00:00
let nKey = bech32.decode(key);
let buff = bech32.fromWords(nKey.words);
let hexKey = secp.utils.bytesToHex(Uint8Array.from(buff));
2022-12-29 10:51:32 +00:00
if (secp.utils.isValidPrivateKey(hexKey)) {
2022-12-27 23:46:13 +00:00
dispatch(setPrivateKey(hexKey));
} else {
throw "INVALID PRIVATE KEY";
}
} else {
2022-12-29 10:51:32 +00:00
if (secp.utils.isValidPrivateKey(key)) {
2022-12-27 23:46:13 +00:00
dispatch(setPrivateKey(key));
} else {
throw "INVALID PRIVATE KEY";
}
}
}
2023-01-01 10:44:38 +00:00
async function makeRandomKey() {
let newKey = secp.utils.bytesToHex(secp.utils.randomPrivateKey());
dispatch(setPrivateKey(newKey))
2023-01-01 19:57:27 +00:00
navigate("/new");
2023-01-01 10:44:38 +00:00
}
2022-12-29 10:51:32 +00:00
async function doNip07Login() {
let pubKey = await window.nostr.getPublicKey();
2022-12-29 15:21:03 +00:00
dispatch(setNip07PubKey(pubKey));
2022-12-29 10:51:32 +00:00
}
function altLogins() {
let nip07 = 'nostr' in window;
if (!nip07) {
return null;
}
return (
<>
<h2>Other Login Methods</h2>
<div className="flex">
<div className="btn" onClick={(e) => doNip07Login()}>Login with Extension (NIP-07)</div>
</div>
</>
)
}
2022-12-18 14:51:47 +00:00
return (
2022-12-27 23:46:13 +00:00
<>
<h1>Login</h1>
<p>Enter your private key:</p>
<div className="flex">
2022-12-29 10:51:32 +00:00
<input type="text" placeholder="Private key" className="f-grow" onChange={e => setKey(e.target.value)} />
2023-01-01 10:44:38 +00:00
</div>
<div className="tabs">
2022-12-27 23:46:13 +00:00
<div className="btn" onClick={(e) => doLogin()}>Login</div>
2023-01-01 10:44:38 +00:00
<div className="btn" onClick={() => makeRandomKey()}>Generate Key</div>
2022-12-27 23:46:13 +00:00
</div>
2022-12-29 10:51:32 +00:00
{altLogins()}
2022-12-27 23:46:13 +00:00
</>
2022-12-18 14:51:47 +00:00
);
}