@us3r-network/auth
v0.2.5-alpha.1
Published
The @us3r-network/auth is a pure javascript lib to create authenticated sessions for users. It could establishes a session with Ceramic through [DIDSession](https://github.com/ceramicnetwork/js-did/tree/main/packages/did-session).
Downloads
15
Keywords
Readme
@us3r-network/auth
The @us3r-network/auth is a pure javascript lib to create authenticated sessions for users. It could establishes a session with Ceramic through DIDSession.
Install
npm install @us3r-network/auth
Usage
Initialize DiDSession from localStorage
import { Us3rAuth } from "@us3r-network/auth";
const us3rAuth = new Us3rAuth();
us3rAuth.init();
DiDSession generated by chain authorization
Ethereum authentication
us3rAuth.auth("ethereum", {
// use any injected web3 provider that implements the standard interface with EthereumWebAuth
provider: window.ethereum,
chainId: "1",
resources: ["ceramic://*"],
});
// The second parameter is the configuration options, where the options are optional, the above is the default value
Check out @didtools/pkh-ethereum to learn more.
Solana authentication
us3rAuth.auth("solana", {
// use any injected Solana provider that implements the standard wallet/provider interface with SolanaWebAuth
provider: window.phantom.solana,
network: "mainnet",
resources: ["ceramic://*"],
});
// The second parameter is the configuration options, where the options are optional, the above is the default value
Check out @didtools/pkh-solana to learn more.
DiDSession Instance
/**
* Get the session instance
*/
const session = us3rAuth.session;
/**
* Delete the session instance and the session string from localStorage
*/
us3rAuth.removeSession();
There are some useful tool methods in the session instance, check out did-session to learn more.
Typical usage pattern
React
import { Us3rAuth } from "@us3r-network/auth";
const us3rAuthInstance = new Us3rAuth();
// ......
const [ isLogin, setIsLogin ] = useState(false)
const login = async ()=>{
await us3rAuthInstance.auth('ethereum')
setIsLogin(true)
}
const logout = async ()=>{
await us3rAuthInstance.removeSession()
setIsLogin(false)
}
useEffect(() => {
await us3rAuthInstance.init();
const session = us3rAuthInstance.session
if (!session || (session.hasSession && session.isExpired)) {
setIsLogin(false)
} else {
setIsLogin(true)
}
},[])
// ......
<button onClick={()=>{
if(isLogin){
logout()
} else {
login()
}
}}>
{isLogin ? 'Logout' : 'Login'}
</button>
// ......