【发布时间】:2018-08-08 12:28:05
【问题描述】:
我正在尝试使用 firebase、react 和 redux 构建基于角色的身份验证。 在从应用程序级别创建新用户时,是否可以将自定义属性(例如“权限”或“角色”)添加到 Firebase 用户对象,或者我应该以其他方式完成?
@更新 - 问题已解决 我按照@frank-van-puffelen 的建议,使用 custom claim 构建了基于角色的 firebase 身份验证。共有三个角色:管理员、工人和客户。只有管理员才能创建工作人员帐户,客户通过 google+ 登录。
我使用 firebase 云功能创建工作帐户,(因为当我尝试在本地执行此操作时,我使用新创建的帐户自动登录),然后设置包含用户角色的自定义声明. Cloud 函数还在解码一个 token,其中包含自定义声明。
这是我的代码 sn-ps:
云功能
const functions = require('firebase-functions');
const cors = require('cors');
const corsHandler = cors({origin: true});
const admin = require('firebase-admin');
admin.initializeApp();
exports.createWorkerAccount = functions.https.onRequest((request, response) => {
corsHandler(request, response, () => {
response.status(200).send('Hello from Cloud Function');
});
admin.auth().createUser({
email: request.body.email,
password: request.body.password
}).then(() => {
admin.auth().getUserByEmail(request.body.email).then((user) => {
admin.auth().setCustomUserClaims(user.uid, {role: 'worker'});
});
});
});
exports.getToken = functions.https.onRequest((request, response) => {
const token = admin.auth().verifyIdToken(request.body.token) //decoding token that contains custom claims
.then((t) => {
corsHandler(request, response, () => {
response.status(200).send(t.role); //sending role as a response
});
});
});
这两个函数都由简单的 ajax 请求调用。
用户的角色作为请求响应返回,然后被推送到 redux 状态,因此我可以从应用程序的任何地方访问它。
要将登录用户重定向到特定路径并对其进行限制,我正在使用 react-router 公共和私有路径以及 firebase 函数 onAuthStateChanged。
检测 firebase 身份验证状态更改 - 它根据自定义声明将用户重定向到特定路径。
firebase.auth().onAuthStateChanged((user) => {
if (user) {
store.dispatch(login(user.uid));
firebase.auth().currentUser.getIdToken() //getting current user's token
.then((t) => {
getTokenRequest(t) // Promise containing the reqest
.then((role) => {
store.dispatch(permissions(role)); //dispatching role to store
renderApp();
if (role == "admin") {
console.log('admin');
history.push('/admin/dashboard'); //redirecting to user-role-specific path
}
else if (role == "worker") {
history.push('/worker/dashboard');
}
else {
history.push('/customer/dashboard');
}
});
});
} else {
store.dispatch(logout());
renderApp();
history.push('/');
}
});
React-router 公共路由组件,它不允许用户访问错误的路径。
export const PublicRoute = ({
isAuthenticated,
role,
component: Component,
...rest
}) => (
<Route {...rest} component={(props) => {
if(isAuthenticated && role == "admin") {
return <Redirect to="/admin/dashboard" />
} else if (isAuthenticated && role == "") {
return <Redirect to ="/customer/dashboard" />
}
else {
return <Component {...props} />
}
}} />
);
const mapStateToProps = (state) => ({
isAuthenticated: !!state.auth.uid,
role: state.role
});
export default connect(mapStateToProps)(PublicRoute);
【问题讨论】:
标签: reactjs firebase redux firebase-authentication roles