[英]Check if user isLoggedIn MongoDB Realm Web SDK
I wish to check if a user is already logged in through email/password auth via mongodb realm web-sdk.我想检查用户是否已经通过 mongodb realm web-sdk 通过电子邮件/密码身份验证登录。 Knowing if the user is logged in will allow me to hide the loggin page from site and instead show a log out button.
知道用户是否已登录将允许我从站点隐藏登录页面,而是显示一个注销按钮。
So far I've successfully created a user and logged in. Using the code/methods below.到目前为止,我已经成功创建了一个用户并登录了。使用下面的代码/方法。
async function registerEmailPassword(email, password) {
try {
const user = await app.emailPasswordAuth.registerUser({ email, password });
return user;
} catch (error) {
console.error("Failed to register", error)
}
}
async function loginEmailPassword(email, password) {
// Create an email/password credential
const credentials = Realm.Credentials.emailPassword(email, password);
try {
// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);
return user;
} catch (error) {
console.error("Failed to log in", error);
}
}
While going through the mongodb class documentation , I wrote the following function which appears to work.在浏览mongodb class 文档时,我写了以下 function,它似乎有效。
The code is checking for if their is any user in currentUser
, if their is no currentUser
, their no account logged in. In the event their is a currentUser
, the code then checks using currentUser.isLoggedIn
if that user is logged and at the end returns a boolean value.该代码正在检查他们是否是
currentUser
中的任何用户,如果他们不是currentUser
,则他们没有登录帐户。如果他们是currentUser
,则代码然后使用currentUser.isLoggedIn
检查该用户是否已登录并在最后返回 boolean 值。
async function isUserLoggedIn() {
try {
const userStatus = await app.currentUser;
if (userStatus == null) {
return false
} else {
const userStatus = await app.currentUser.isLoggedIn;
return userStatus
}
} catch (error) {
console.log("Failed to fetch user", error);
}
}
// Check if user is logged in
isUserLoggedIn().then((value) => {
console.log(value);
}).catch((error) => {
console.log(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.